Friday, 22 January 2021

Push Notification using Amazon SNS (Xamarin.IOS)

Push is an incredible and necessary feature in any mobile application. Amazon's AWS provides a push service for mobile through it's amazing Simple Notifications Service (SNS).

Generate APNS certificate for iOS Push Notifications Checkout this

First of all please go and read to setup CONSOLE of AMAZON-AWS SNS 

https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/getting-started-sns-ios.html

Then follow the below steps in xamairn forms projects

we required below NUGET package for this : VERSION - YOU CAN USE LATEST NO ISSUE ON THIS.


Then in App Delegate File we have to write below code for Notification setting : 

using UIKit;

using System;

using Foundation;

using Xamarin.Forms;

using System.Linq;


namespace SNSAmazon.iOS

{


    [Register("AppDelegate")]

    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate

    {

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)

        {

            Window = new TouchWindow(UIScreen.MainScreen.Bounds);

            global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");

            UIApplication.SharedApplication.IdleTimerDisabled = true;

            var init = new Init();

            Window.MakeKeyAndVisible();

             LoadApplication(new App(init));

            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(

              UIUserNotificationType.Alert |

              UIUserNotificationType.Badge |

              UIUserNotificationType.Sound,

              null

            );

            app.RegisterUserNotificationSettings(pushSettings);

            app.RegisterForRemoteNotifications();

            return base.FinishedLaunching(app, options);

        }

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData token)

        {

            var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", "");

            byte[] bytes = token.ToArray<byte>();

            string[] hexArray = bytes.Select(b => b.ToString("x2")).ToArray();

            var UniqueDeviceID = string.Join(string.Empty, hexArray);

            if (!string.IsNullOrEmpty(deviceToken))

            {

                SNSUtils.RegisterDevice(SNSUtils.Platform.IOS, deviceToken);

            }

        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)

        {

            Console.WriteLine(@"Failed to register for remote notification {0}", error.Description);

        }

Note this UniqueDeviceID is required to Push Notification on Console on amazon SNS


    SNSUtils.RegisterDevice(SNSUtils.Platform.IOS, deviceToken);

Now  SNSUtils class in Portable Project


using System.Threading.Tasks;

using Amazon.CognitoIdentity;

using Amazon.Runtime;

using Amazon.SimpleNotificationService;

using Amazon.SimpleNotificationService.Model;

namespace SNSAmazon

{

    public class SNSUtils

    {

        public enum Platform

        {

            Android,

            IOS,

            WindowsPhone

        }

        private static AWSCredentials _credentials;

        private static AWSCredentials Credentials

        {

            get

            {

                if (_credentials == null)

                    _credentials = new CognitoAWSCredentials(AWSConstants.IdentityPoolId, AWSConstants.CognitoRegion);

                return _credentials;

            }

        }

        private static IAmazonSimpleNotificationService _snsClient;

        private static IAmazonSimpleNotificationService SnsClient

        {

            get

            {

                if (_snsClient == null)

                    _snsClient = new AmazonSimpleNotificationServiceClient(Credentials, AWSConstants.SnsRegion);

                return _snsClient;

            }

        }

        public static async Task RegisterDevice(Platform platform, string registrationId)

        {

            var arn = string.Empty;

            string _endpointArn = string.Empty;

            switch (platform)

            {

                case Platform.Android:

                    arn = AWSConstants.AndroidPlatformApplicationArn;

                    break;

                case Platform.IOS:

                    arn = AWSConstants.iOSPlatformApplicationArn;

                    break;

            }

            var response = await SnsClient.CreatePlatformEndpointAsync(new CreatePlatformEndpointRequest

            {

                Token = registrationId,

                PlatformApplicationArn = arn

            }

            );

            _endpointArn = response.EndpointArn;

        }

    }

}

AWSConstants.cs file contains your configuration settings

using System;
using Amazon;
namespace SNSAmazon
{
    public class AWSConstants
    {
        //identity pool id for cognito credentials
        public const string IdentityPoolId = "TODO";
        //sns android platform arn
        public const string AndroidPlatformApplicationArn = "TODO";
        //sns ios platform arn
        public const string iOSPlatformApplicationArn = "TODO";
        public const string GoogleConsoleProjectId = "test";  // Sender ID not ProjectID
        public static RegionEndpoint CognitoRegion = RegionEndpoint.USEast1;
        public static RegionEndpoint SnsRegion = RegionEndpoint.USEast1;
    }
}

Please Remember :

you should enable Background Modes/Remote notifications to be able to use remote notifications for background updates.

The easiest way to do this is via the project settings. Navigate to Targets -> Your App -> Capabilities -> Background Modes and check Remote notifications. This will automatically enable the required settings.

Background Modes dropdown list in Project Settings


Ref Link , Link2 (GitHub)


1 comment:

  1. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development

    ReplyDelete

All About .NET MAUI

  What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

Ads2