Fetch Firebase push notification data without clicking notification - Xamarin.forms iOS

寵の児 提交于 2020-07-16 08:06:09

问题


Hi I have a xamarin forms ios application implemented with firebase push notifications. I can receive and mange the click of notifications. Currently I am trying to store the notification data ie; Title,body and two other parameters comes with notification in to sqlite database. I can retrieve and store the data when user clicks. But cant store if user swipe away the notification. How can I get the values as soon as notification appear? Any help is appriciated.

My AppDelegate


  [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate
    {     
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {           
            global::Xamarin.Forms.Forms.Init();    
            Firebase.Core.App.Configure();
            LoadApplication(new App());
     
            //<-------Firebase Implementation------------->

            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();
            Messaging.SharedInstance.Delegate = this;
            Messaging.SharedInstance.ShouldEstablishDirectChannel = true;


            return base.FinishedLaunching(app, options);
        }

        //<--------Firebase Portion------->

        [Export("messaging:didReceiveRegistrationToken:")]
        public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
        {       
            Settings.FirebaseRegID = fcmToken;
            MessagingCenter.Send<object, string>(this, "fcmtoken", fcmToken.ToString());
            Console.WriteLine($"fcmtoken received: {fcmToken}");
        }

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {         
            HandleMessage(userInfo);        
            LogInformation(nameof(DidReceiveRemoteNotification), userInfo);
            completionHandler(UIBackgroundFetchResult.NewData);                  
            if (UIApplication.SharedApplication.ApplicationState.Equals(UIApplicationState.Active))
            {
                //App is in foreground. Act on it.  
            }
            else
            {
                // MessagingCenter.Send<object, List<key>>(this, "messagedata", myData);
            }
        }

        //User for showing the notification in foreground mode
        [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
        public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,
        Action<UNNotificationPresentationOptions> completionHandler)
        {
            completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);
        }

        //Foreground mode notification tapping handling here
        [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
        public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action
        completionHandler)
        {
            completionHandler();
            NSDictionary userInfo = response.Notification.Request.Content.UserInfo;           
            try
            {               
                var Data = userInfo[new NSString("gcm.notification.data")] as NSString;
                if (Data != null && Data != "")
                {
                    string[] tokens = Data.ToString().Split(',');
                    string Username = tokens[0];
                    string Password = tokens[1];
                    var Title = string.IsNullOrEmpty(response.Notification.Request.Content.Title)?"No Notification available": response.Notification.Request.Content.Title;
                    var Body = string.IsNullOrEmpty(response.Notification.Request.Content.Body)?"No Message available": response.Notification.Request.Content.Body;        
                    MessagingCenter.Send(new NotificationData() { TItle = Title.ToString(), Body = Body.ToString(),username= Username ,Password= Password }, "iosnotificationTapped");                 
                }       
            }
            catch (Exception ex)
            {

            }
        }

        [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)
        {
            var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert);
            alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (obj) => actionForOk?.Invoke()));
            fromViewController.PresentViewController(alert, true, null);
        }

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

EDIT I tried to put debugger on

void DidReceiveRemoteNotification,void DidReceiveMessage,void HandleMessage

None of them hit when notification appears. Only DidReceiveNotificationResponse will hit if we tap the notification. In android there is onmessagereceived which will hit when notification arrives. Does iOS have such method?

来源:https://stackoverflow.com/questions/62673761/fetch-firebase-push-notification-data-without-clicking-notification-xamarin-fo

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