Xamarin iOS推送通知背景和前景问题

时间:2020-03-02 08:19:39

标签: xamarin xamarin.forms xamarin.ios azure-notificationhub

我一直试图在Xamarin iOS App中添加针对iOS 10的推送通知,但是

Foreground我第一次在UNUserNotificationCenterDelegate中成功地收到了部署通知,但是第二次它没有捕获到通知,除非我卸载了该应用程序并重新安装它。

Background我总是收到通知,但无法捕获它的点击。 InActive工作正常,我可以在FinishedLaunching中捕获其点击。

代码

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
       // Remote Notifications
       SetupRemoteNotifications(app, options);
    }

    private void SetupRemoteNotifications(UIApplication app, NSDictionary options)
            {
                // Handling multiple OnAppear calls
                if (!UIApplication.SharedApplication.IsRegisteredForRemoteNotifications)
                {
                    // register for remote notifications based on system version
                    if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
                    {
                        // iOS 10 or later
                        var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
                        UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
                        {
                            if (granted)
                            {
                                InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                            }
                        });

                        // Watch for notifications while the app is active
                        UNUserNotificationCenter.Current.Delegate = this;
                    }
                    else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                    {
                        var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                        UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                        new NSSet());

                        UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                        UIApplication.SharedApplication.RegisterForRemoteNotifications();
                    }
                    else
                    {
                        UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                        UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                    }
                }

                // Check for a notification
                if (options != null)
                {
                    // check for a remote notification
                    if (options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
                    {

                        var remoteNotification = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
                        if (remoteNotification != null)
                        {
                            ProcessNotification(remoteNotification, true);
                            //new UIAlertView(remoteNotification.AlertAction, remoteNotification.AlertBody, null, "OK", null).Show();
                        }
                    }
                }
            }

[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
        public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response,
            Action completionHandler)
        {
            var userInfo = response.Notification.Request.Content.UserInfo;

            if (userInfo != null && userInfo.ContainsKey(new NSString("aps")))
            {
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

                NSDictionary message = aps.ObjectForKey(new NSString("alert")) as NSDictionary;
                NSDictionary metadataNSDict = aps.ObjectForKey(new NSString("metadata")) as NSDictionary;

                var metaDataDict = metadataNSDict.ConvertToDictionary();
                var metaJson = metaDataDict.FromDictionaryToJson();
                var metadata = JsonConvert.DeserializeObject<NotificationMetadata>(metaJson);

                if (message != null && metadata != null)
                {
                    NotificationGoToPage(metadata);
                }
            }

            completionHandler();
        }

        [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
        public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,
            Action<UNNotificationPresentationOptions> completionHandler)
        {
            // Do something with the notification
            Console.WriteLine("Active Notification: {0}", notification);

            // Tell system to display the notification anyway or use
            // `None` to say we have handled the display locally.
            completionHandler(UNNotificationPresentationOptions.Alert |
                UNNotificationPresentationOptions.Sound |
                UNNotificationPresentationOptions.Badge);
        }



        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
            ProcessNotification(userInfo, false);
        }

即使我尝试使用DidReceiveRemoteNotification,但这也无法捕获Background

[Export("didReceiveRemoteNotification:")]
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo,
            Action<UIBackgroundFetchResult> completionHandler)
        {
            if (application.ApplicationState == UIApplicationState.Active)
            {
                completionHandler(UIBackgroundFetchResult.NoData);
            }
            else if (application.ApplicationState == UIApplicationState.Background)
            {

            }
            else
            {
                completionHandler(UIBackgroundFetchResult.NoData);
            }
        }

Entitlements.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aps-environment</key>
    <string>production</string>
</dict>
</plist>

Info.plist

<key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>

1 个答案:

答案 0 :(得分:0)

尝试一下:

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    NSString title = ((userInfo["aps"] as NSDictionary)["alert"] as NSDictionary)["title"] as NSString;
    NSString message = ((userInfo["aps"] as NSDictionary)["alert"] as NSDictionary)["body"] as NSString;

    if (!App.IsMinimized) // check if app is minimized
    {
        // your logic
    }

}

在您的应用中

public static bool IsMinimized { set; get; } = false;

    protected override void OnStart()
    {
        // Handle when your app starts
        IsMinimized = false;
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
        IsMinimized = true;

    }

    protected override void OnResume()
    {
        // Handle when your app resumes
        IsMinimized = false;
    }
相关问题