简体   繁体   中英

FCM Background Notification on IOS app in Xamarin C# not working

The team is developing an IOS app on Xamarin in c# . Now we wanted to use the push notification service of fcm . Tried deploying the app but the issue is : The notifications are not received on ios if the app is in background. Did some research on it but found that the app disconnects from fcm when goes in background. Although tried not to disconnect it by not invoking the function but still the notifications were not received. Just wanted to know whether it's possible to receive the notification on ios while the app is in the background. Sharing the relevant link and also the code for background that disconnects the app from fcm when it goes in background. Also removed the function call but it did not work.

public override void DidEnterBackground (UIApplication application)
{
    // Use this method to release shared resources, save user data, 
    //invalidate timers and store the application state.
    // If your application supports background exection this method is 
    //called instead of WillTerminate when the user quits.
    Messaging.SharedInstance.Disconnect ();
    Console.WriteLine (“Disconnected from FCM”);
}

Link: https://components.xamarin.com/gettingstarted/firebaseioscloudmessaging/true

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        App.Configure ();

        // Register your app for remote notifications.
        if (UIDevice.CurrentDevice.CheckSystemVersion (10, 0)) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.Current.Delegate = this;

            var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
            UNUserNotificationCenter.Current.RequestAuthorization (authOptions, (granted, error) => {
                Console.WriteLine (granted);
            });
        } 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 ();

        Messaging.SharedInstance.Delegate = this;

        // To connect with FCM. FCM manages the connection, closing it
        // when your app goes into the background and reopening it 
        // whenever the app is foregrounded.
        Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
        return true;
    }

Next put this in the AppDelegate.cs

[Export("messaging:didReceiveRegistrationToken:")]
    public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
    {
        // Monitor token generation: To be notified whenever the token is updated.

        LogInformation(nameof(DidReceiveRegistrationToken), $"Firebase registration token: {fcmToken}");

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    // You'll need this method if you set "FirebaseAppDelegateProxyEnabled": NO in GoogleService-Info.plist
    //public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
    //{
    //  Messaging.SharedInstance.ApnsToken = deviceToken;
    //}

    public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        // Handle Notification messages in the background and foreground.
        // Handle Data messages for iOS 9 and below.
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        //Messaging.SharedInstance.AppDidReceiveMessage (userInfo);

        if(ConnectionClass.CompanyID != null)
        {
            SyncData.SyncDataDB();
        }
        //FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Alert;
        FirebasePushNotificationManager.DidReceiveMessage(userInfo);
        //HandleMessage(userInfo);

        // Print full message.
        //LogInformation(nameof(DidReceiveRemoteNotification), userInfo);

        //completionHandler(UIBackgroundFetchResult.NewData);
    }

    [Export("messaging:didReceiveMessage:")]
    public void DidReceiveMessage(Messaging messaging, RemoteMessage remoteMessage)
    {
        // Handle Data messages for iOS 10 and above.
        HandleMessage(remoteMessage.AppData);

        LogInformation(nameof(DidReceiveMessage), remoteMessage.AppData);
    }

    void HandleMessage(NSDictionary message)
    {
        if (MessageReceived == null)
            return;

        MessageType messageType;
        if (message.ContainsKey(new NSString("aps")))
            messageType = MessageType.Notification;
        else
            messageType = MessageType.Data;

        var e = new UserInfoEventArgs(message, messageType);
        MessageReceived(this, e);
    }

    public static void ShowMessage(string title, string message, UIViewController fromViewController, Action actionForOk = null)
    {
        if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
            alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (obj) => actionForOk?.Invoke()));
            fromViewController.PresentViewController(alert, true, null);
        }
        else
        {
            var alert = new UIAlertView(title, message, null, "Ok", null);
            alert.Clicked += (sender, e) => actionForOk?.Invoke();
            alert.Show();
        }
    }

    void LogInformation(string methodName, object information) => Console.WriteLine($"\nMethod name: {methodName}\nInformation: {information}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM