DIGITAL JEDI
DIGITAL JEDI

Reputation: 1666

Xamarin Form(PCL) IOS Firebase Push Message not working

I created a xamarin form project and I integrated firebase push notification in both Android & IOS projects. Its working fine on Android but not working with iOS. I downloaded and added GoogleService-info.plist in iOS project, Set its Build Action to BundleResource.

AppDelegates.cs

    namespace PushNotification.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            RegisterForNotificationFCM();

            return base.FinishedLaunching(app, options);
        }


        private void RegisterForNotificationFCM()
        {

            //Firebase Cloud Messaging Configuration

            //Get permission for notification
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                // iOS 10
                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;

                Messaging.SharedInstance.RemoteMessageDelegate = this as IMessagingDelegate;

            }
            else
            {
                // iOS 9 <=
                var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            }

            UIApplication.SharedApplication.RegisterForRemoteNotifications();

            Firebase.Analytics.App.Configure();

            Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
            {
                var newToken = Firebase.InstanceID.InstanceId.SharedInstance.Token;
                System.Diagnostics.Debug.WriteLine(newToken);

                connectFCM();
            });

        }


        public override void DidEnterBackground(UIApplication uiApplication)
        {
            Messaging.SharedInstance.Disconnect();
        }

        public override void OnActivated(UIApplication uiApplication)
        {
            connectFCM();
            base.OnActivated(uiApplication);
        }

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            Firebase.InstanceID.InstanceId.SharedInstance.SetApnsToken(deviceToken, Firebase.InstanceID.ApnsTokenType.Prod);
        }

        //Fire when background received notification is clicked
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            //Messaging.SharedInstance.AppDidReceiveMessage(userInfo);
            System.Diagnostics.Debug.WriteLine(userInfo);

            // Generate custom event
            NSString[] keys = { new NSString("Event_type") };
            NSObject[] values = { new NSString("Recieve_Notification") };
            var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);

            // Send custom event
            Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);

            if (application.ApplicationState == UIApplicationState.Active)
            {
                System.Diagnostics.Debug.WriteLine(userInfo);
                var aps_d = userInfo["aps"] as NSDictionary;
                var alert_d = aps_d["alert"] as NSDictionary;
                var body = alert_d["body"] as NSString;
                var title = alert_d["title"] as NSString;
                debugAlert(title, body);
            }
        }

        private void connectFCM()
        {
            Messaging.SharedInstance.Connect((error) =>
            {
                if (error == null)
                {
                    Messaging.SharedInstance.Subscribe("/topics/topicName");
                }
                System.Diagnostics.Debug.WriteLine(error != null ? "error occured" : "connect success");
            });
        }

        private void debugAlert(string title, string message)
        {
            var alert = new UIAlertView(title ?? "Title", message ?? "Message", null, "Cancel", "OK");
            alert.Show();
        }


    }
}

Added all required Firebase libraries in IOS project & its building fine. But notification is not receiving on IOS simulator. Tell me what I am missing.

Upvotes: 1

Views: 2656

Answers (2)

Frank Fitzgerald
Frank Fitzgerald

Reputation: 21

SOLVED

I had this same problem and was dealing with it for a day or two. The problem came down to the selected provisioning profile that was being used. When I changed my app id in the apple development portal to use push notification and downloaded my provisioning profile it created a second profile with the same name downloaded. This caused an error when it tried to select the correct one. Deleted the old provisioning profile and all is well now.

Upvotes: 2

iamIcarus
iamIcarus

Reputation: 1438

You cannot test push notification in the simulator

Please take a look on the Prerequisites.

For Cloud Messaging:

 - A physical iOS device 
 - APNs certificate with Push Notifications enabled
 - In Xcode, enable Push Notifications in App > Capabilities

Upvotes: 0

Related Questions