首页 > 解决方案 > 如何处理推送通知中的点击事件 (Xamarin.IOS)

问题描述

在 xamarin.ios 项目中,当用户通过单击推送通知打开应用程序时,我需要发出特定的警报。

在我当前的代码中,我处理GUID, Type即将到来的通知的特定数据,并使用它来加载此通知所需的数据(LoadItemData)。但是我没有找到处理点击事件的方法,所以如果我在 1 次有多个通知,单击这些推送通知中的任何一个都会有一个结果。

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{   
    if (uiapplication.sharedapplication.applicationstate.equals(uiapplicationstate.background))
    {
        string GUID = (userInfo[new NSString("Item_Guid")] as NSString).ToString();
        string Type = (userInfo[new NSString("Type")] as NSString).ToString();
        nsdictionary aps = userinfo.objectforkey(new nsstring("aps")) as nsdictionary;

        string alertinfo = string.empty;
        if (aps.containskey(new nsstring("alert")))
            alertinfo = (aps[new nsstring("alert")] as nsstring).tostring();

        var okcancelalertcontroller = uialertcontroller.create("New Notification", alertinfo, uialertcontrollerstyle.alert);
        okcancelalertcontroller.addaction(uialertaction.create("Open", uialertactionstyle.default, alert => LoadItemData(guid, type)));
        okcancelalertcontroller.addaction(uialertaction.create("OK", uialertactionstyle.cancel, alert => console.writeline("cancel was clicked")));
        uiapplication.sharedapplication.keywindow.rootviewcontroller.presentviewcontroller(okcancelalertcontroller, true, null);
    }
}   

标签: xamarinxamarin.formsxamarin.ios

解决方案


在 iOS 10 之后,Apple 替换UIUserNotificationUNNotification.So 在你的应用中使用新的 Delegate。

例如

在 AppDelegate

public class AppDelegate : UIApplicationDelegate,IUNUserNotificationCenterDelegate
...


[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler)
    {

        if(UIApplication.SharedApplication.ApplicationState==UIApplicationState.Active)
        {
            // app is active,do some thing you want
        }


        else
        {
            // app is in background ,do some thing you want
        }

        completionHandler();

这是您可以参考 的类似问题。


推荐阅读