Xamarin.iOS RegisteredForRemoteNotifications not c

2019-07-03 23:57发布

问题:

I am using Xamarin Forms and am currently trying to get push notifications to work with the iOS project. I have followed this Xamarin guide to add notifications to my iOS app but the RegisteredForRemoteNotifications method is never called.

I have also created both push notification certificates and enabled background notifications. Even FailedToRegisterForRemoteNotifications is never called.

What can I do?

PS: I'm using an iPhone 5s with iOS 10 so I also read this post on the User Notifications Framework.

回答1:

Points for noticing the big note at the top of the Xamarin guide, a lot of people sometimes gloss over them.

NOTE: The information in this section pertains to iOS 9 and prior, it has been left here to support older iOS versions. For iOS 10 and later, please see the User Notification Framework guide for supporting both Local and Remote Notification on an iOS device.

It would have been nice to see some of your own code sample, but that's neither here nor there.

So as you said you plan on using iOS 10 devices, here is the code we use that works from 10.3 backwards.This code is in our FinishedLaunching() method inside the AppDelegate class.

            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                // iOS 10 or later
                var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
                UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
                {
                    if (granted)
                    {
                        InvokeOnMainThread(() => {
                            UIApplication.SharedApplication.RegisterForRemoteNotifications();
                        });
                    }
                });

                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.Current.Delegate = ADSelf;
            }
            else
            {
                // iOS 9 or before
                var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            }

The key really is the following lines:

UIApplication.SharedApplication.RegisterForRemoteNotifications();

OR

UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);


回答2:

So, after publishing in the AppStore it starts working...



回答3:

I was having the same issue. The fault was, the mobile phone didn't have an active internet connection!



回答4:

You cannot register the device if it is a simulated device.