简体   繁体   中英

Xamarin.iOS app does not receive parse.com PUSH when active

I can send pushes to my users both through parse.com and through their API from my website.

But the pushes ONLY arrive if the app is inactive, eg either in the background or turned/killed off. If the app is the active app then the push does not appear.

I want the push to arrive like it does outside the app(eg a notification that appears at the top and appears in the notification log in iOS)

My code is made in Xamarin.iOS and uses practically the default parse.com Xamarin.iOS pre-made template.

What is it that I should change to make it receive pushes and treat them like normally even while the app is active?

This app has been published and works both live & while debugging. But the pushes not arriving when active is my issue here.

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // Initialize the Parse client with your Application ID and .NET Key found on
            // your Parse dashboard
            ParseClient.Initialize("key1", "key2");

            // Register for Push Notitications
            UIUserNotificationType notificationTypes = (UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound);
            var settings = UIUserNotificationSettings.GetSettingsForTypes(notificationTypes, new NSSet(new string[] { }));
            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();

            // Handle Push Notifications
            ParsePush.ParsePushNotificationReceived += (object sender, ParsePushNotificationEventArgs args) => {
                // Process Push Notification payload here.
            };

            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }

        public override void DidRegisterUserNotificationSettings(UIApplication application, UIUserNotificationSettings notificationSettings)
        {
            application.RegisterForRemoteNotifications();
        }

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            ParseObject obj = ParseObject.Create("_Installation");

            string dt = deviceToken.ToString().Replace("<", "").Replace(">", "").Replace(" ", "");
            obj["deviceToken"] = dt;
            obj.SaveAsync().ContinueWith(t => {
                if (t.IsFaulted)
                {
                    using (IEnumerator<System.Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator())
                    {
                        if (enumerator.MoveNext())
                        {
                            ParseException error = (ParseException)enumerator.Current;
                        }
                    }
                }
                else
                {
                    var data = NSUserDefaults.StandardUserDefaults;
                    data.SetString("currentInstallation", obj.ObjectId);
                }
            });

            parseDeviceInfo.deviceToken = dt;

            //Original parse.com code that does not work
            //ParseInstallation installation = ParseInstallation.CurrentInstallation;
            //installation.SetDeviceTokenFromData(deviceToken);

            //installation.SaveAsync();
        }

        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            // We need this to fire userInfo into ParsePushNotificationReceived.
            ParsePush.HandlePush(userInfo);
        }

Thank you for your time.

Here is the solution.

Inside ParsePush.ParsePushNotificationReceived that can be seen above

// Process Push Notification payload here.

                string message = "";

                try
                {

                    var payload = args.Payload;
                    object aps;
                    if (payload.TryGetValue("aps", out aps))
                    {
                        string payloadStr = "";

                        try
                        {
                            payloadStr = aps.ToString();
                        }
                        catch (Exception e)
                        {
                        }

                        try
                        {
                            var match = Regex.Match(payloadStr, @"alert = (.*);\n");
                            if (match.Success)
                            {
                                string alertText = match.Groups[1].Value;
                                message = alertText;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                catch (Exception e)
                {
                    message = "payload crash";
                }

                if (string.IsNullOrEmpty(message))
                    message = "";

                UILocalNotification notification = new UILocalNotification();
                //NSDate.FromTimeIntervalSinceNow(15);
                notification.FireDate = NSDate.FromTimeIntervalSinceNow(5);
                //notification.AlertTitle = "Alert Title"; // required for Apple Watch notifications
                notification.AlertAction = "Message";
                notification.AlertBody = message;
                notification.SoundName = UILocalNotification.DefaultSoundName;
                UIApplication.SharedApplication.ScheduleLocalNotification(notification);

Also need to add this function This is also in AppDelegate

public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
        {
            try
            {
                // show an alert
                UIAlertController okayAlertController = UIAlertController.Create(notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert);
                okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                //viewController.PresentViewController(okayAlertController, true, null);

                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(okayAlertController, true, null);

                // reset our badge
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
            }
            catch (Exception)
            {
            }
        }

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