Search code examples
iospush-notificationxamarin.iosapple-push-notifications

How to access parameters in Push Notification


I am using mvvmCross 5.3 and Xamarin 6.3 and need help to access data passed by notification.

When I get a notification, I'm getting a standard JSON that is sent by Apple. I also receive one more parameter that I'll use to point to some screen in my application.

In my AppDelegate, I have the following code:

 public override bool FinishedLaunching(UIApplication application, NSDictionary options)
        {
            Window = new UIWindow(UIScreen.MainScreen.Bounds);

            var setup = new Setup(this, Window);
            setup.Initialize();

            var startup = Mvx.Resolve<IMvxAppStart>();
            startup.Start();

            Window.MakeKeyAndVisible();

            //Push Notifications
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                                   UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                                   new NSSet());

                UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
            }

            return ApplicationDelegate.SharedInstance.FinishedLaunching(application, options);
        }

In the parameter options, I know that I get the information I need. I do not know how to access this information in my code.

2017-10-26 11:39:28.680 App.IOs[6733:2676232] 
{
    UIApplicationLaunchOptionsRemoteNotificationKey =     
    {
        aps =         
        {
            alert =             
            {
                body = "Message";
                title = "Title";
            };
        };
        idOrder = 254;
    };
}

Solution

  • You can create a method like this and call it in the iOS methods that receive the notifications in AppDelegate:

    private void HandleReceivedNotification(NSDictionary userInfo = null)
    {
    
        if (userInfo != null)
        {
            var apsDictionary = userInfo["aps"] as NSDictionary;
            var alertDictionary = apsDictionary["alert"] as NSDictionary;
            var body = alertDictionary["body"].ToString();
            var idOrder = userInfo["idOrder "].ToString();
        }
    }
    

    But don't forget to include a try/catch and check if any variable is null.