Xamarin Forms: Push notification is not receiving to ios device

◇◆丶佛笑我妖孽 提交于 2021-01-28 12:09:24

问题


I have done the following things:

  1. Created a project in FCM console and added ios project into it.
  2. Downloaded the GoogleService-Info.plist and added it to the xamarin forms ios project directory and set the build action as Bundlesource.
  3. On Info.plist enabled remote notification background mode.
  4. Added FirebaseAppDelegateProxyEnabled in the app’s Info.plist file and set it to No.
  5. Created a provisioning profile and distribution certificate and installed it into the keychain access. Also, mapped these certificates in the project options.
  6. Uploaded .p12 certificate in FCM console.
  7. Added codes for handling push notification in AppDelegate.cs.

My Code:

    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App("",""));
            RequestPushPermissionsAsync();
            _launchoptions = options;
            // Register your app for remote notifications.
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            // iOS 10 or later
            var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
            UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
                Console.WriteLine(granted);
            });

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.Current.Delegate = this;

            // For iOS 10 data message (sent via FCM)
            //Messaging.SharedInstance.RemoteMessageDelegate = this;
        }
        else
        {
            // iOS 9 or before
            var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
            var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
        }

        UIApplication.SharedApplication.RegisterForRemoteNotifications();
            return base.FinishedLaunching(app, options);
        }
        NSDictionary _launchoptions;
        public override void OnActivated(UIApplication uiApplication)
        {
            base.OnActivated(uiApplication);
            if (_launchoptions != null && _launchoptions.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
            {
                var notfication = _launchoptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
                PresentNotification(notfication);
            }
            _launchoptions = null;
        }

        async Task RequestPushPermissionsAsync()
        {
            var requestResult = await UNUserNotificationCenter.Current.RequestAuthorizationAsync(
                 UNAuthorizationOptions.Alert
                | UNAuthorizationOptions.Badge
                | UNAuthorizationOptions.Sound);

            bool approved = requestResult.Item1;
            NSError error = requestResult.Item2;
            if (error == null)
            {
                if (!approved)
                {
                    Console.Write("Permission to receive notification was not granted");
                    return;
                }

                var currentSettings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();
                if (currentSettings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
                {
                    Console.WriteLine("Permissions were requested in the past but have been revoked (-Settings  app)");
                    return;
                }
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                Console.Write($"Error requesting permissions: {error}.");
            }
        }

        public async override void RegisteredForRemoteNotifications(
        UIApplication application, NSData deviceToken)
    {
        //if (deviceToken == null)
        //{
        //    // Can happen in rare conditions e.g. after restoring a device.
        //    return;
        //}

        //Console.WriteLine($"Token received: {deviceToken}");

        // Get current device token
        var DeviceToken = deviceToken.Description;
        if (!string.IsNullOrWhiteSpace(DeviceToken))
        {
            DeviceToken = DeviceToken.Trim('<').Trim('>');
        }

        Console.WriteLine($"deviceToken received: {deviceToken}");
        Console.WriteLine($"DeviceToken received: {DeviceToken}");

        // Get previous device token
        var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

        // Has the token changed?
        if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
        {
            //TODO: Put your own logic here to notify your server that the device token has changed/been created!
        }

        // Save new device token
        NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");

        await SendRegistrationToServerAsync(DeviceToken);
    }

        async Task SendRegistrationTokenToMainPRoject(NSData deviceToken)
        {
            MessagingCenter.Send<object, string>(this, "fcmtoken", deviceToken.ToString());
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            Console.WriteLine($"Failed to register for remote notifications: {error.Description}");
        }

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo,
            Action<UIBackgroundFetchResult> completionHandler)
        {
            PresentNotification(userInfo);
            completionHandler(UIBackgroundFetchResult.NoData);
            try
            {
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
                var message = (aps[new NSString("webContentList")] as NSString).ToString();
                LoadApplication(new App("", message));
            }
            catch (Exception ex)
            {
                //LogInfo.ReportErrorInfo(ex.Message, ex.StackTrace, "AppDelegate-DidReceiveRemoteNotification");
            }
        }

        void PresentNotification(NSDictionary userInfo)
        {
            NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

            var msg = string.Empty;

            if (aps.ContainsKey(new NSString("alert")))
            {
                msg = (aps[new NSString("alert")] as NSString).ToString();
            }
            if (string.IsNullOrEmpty(msg))
            {
                msg = "(unable to parse)";
            }
            MessagingCenter.Send<object, string>(this, App.NotificationReceivedKey, msg);
        }
    }

I am not using any NuGet packages in ios part. When running the project into a device, the FCM token generating part is working and I can see the fcm token on the VS console. I tried to send a test notification to a device from postman but getting InvalidRegistration error.

Postman Response

{
    "multicast_id": 8754155136812875313,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "InvalidRegistration"
        }
    ]
}

Postman Body

 {
    "to" : "d20ad003 7473bfba 85dffc33 1534decf b4b886f1 c738878f fd7f2c60 d9dabc36",
 "collapse_key" : "type_a",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 },
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification",
     "sound": "default",
     "content_available" : true
 }
}

I have completed the android part implementation and notifications are receiving when push from the postman. But getting InvalidRegistration error on ios part and not receiving any notification in my ios device.

I follow this youtube video for this implementation and the complete source code is here.

Anyone suggest a solution for this issue.

Thanks in advance.

Update

I have created a sample project and a postman collection and added it to my google folder.

Postman collection contains 2 REST APIs, one for Android device and the other one for ios device

If you import the postman collection and run the Android REST API, I will receive the notification, because I have added my device FCM token on it. But when running the ios REST API in postman will return InvalidRegistration error in postman.

Please go through the sample project and please give me a solution?


回答1:


I have reviewed and can resolve this issue.

  1. Install the plugin Xamarin.Firebase.iOS.CloudMessaging in iOS project.
  2. AppDelegate class needs to inherit from IUNUserNotificationCenterDelegate and IMessagingDelegate interfaces.
  3. Include the Firebase.Core.App.Configure (); in FinishedLaunching method before registering remote notification.
  4. Then you can add the registering remote notification code (You can get the code from given link).
  5. You need to set user notification delegate and messaging shared instant delegate (UNUserNotificationCenter.Current.Delegate = this; // For iOS 10 display notification (sent via APNS) and Messaging.SharedInstance.Delegate = this;).
  6. Include DidReceiveRegistrationToken and DidReceiveMessage methods with corresponding attributes

Please refer this AppDelegate class for more clarity https://github.com/xamarin/GoogleApisForiOSComponents/blob/master/Firebase.CloudMessaging/samples/CloudMessagingSample/CloudMessagingSample/AppDelegate.cs

Related Xamarin Forums thread https://forums.xamarin.com/discussion/159477/xamarin-forms-push-notification-is-not-receiving-to-ios-device#latest



来源:https://stackoverflow.com/questions/56746915/xamarin-forms-push-notification-is-not-receiving-to-ios-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!