当用户关闭应用程序时,如何处理Xamarin iOS上的用户单击本地通知?

时间:2019-09-25 15:22:07

标签: xamarin xamarin.forms xamarin.ios

我的应用程序收到通知并显示本地User Notification

local notification click_open_notification

当用户关闭此应用并单击此本地通知时。

我想处理打开此本地通知的事件。

我尝试了以下链接:

Handle local notification tap Xamarin Forms iOS

但是方法 ReceivedLocalNotification()似乎不起作用(我尝试显示警报,但警报未显示。)

我尝试在方法 DidReceiveRemoteNotification()

中显示警报

类似于Xamarin.iOS - Red & Green Notifications示例,但是我无法处理事件“ 用户在应用程序关闭时单击本地通知”。

这是我的代码:

        [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler)
    {
        // Show Alert 
        var alert = new UIAlertView()
        {
            Title = "LocalNotification",
            Message = $"Content: Method DidReceiveNotificationResponse()"
        };
        alert.AddButton("OK");
        alert.Show();

        if (response.IsDefaultAction)
        {
            Console.WriteLine("ACTION: Default");
        }
        if (response.IsDismissAction)
        {
            Console.WriteLine("ACTION: Dismiss");
        }
        else
        {
            Console.WriteLine($"ACTION: {response.ActionIdentifier}");
        }

        completionHandler();
    }

请帮助我!

如何处理“ 用户在应用程序关闭时单击本地通知”事件? 我正在ios 12.4和ios 13.0上进行测试。

1 个答案:

答案 0 :(得分:2)

您必须在AppDelegate.cs替代中的FinishedLaunching内部进行检查,以了解传递到应用程序中的选项。它将包含推送通知信息。

UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

if (options != null)
{
    if (options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
    {
        NSDictionary dic = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;

        // decide what to do with push info here
    }

    Console.WriteLine($"Startup: {nameof(AppDelegate.FinishedLaunching)} : {nameof(options)} {options}");
}

如果您使用的是ios 10+,则您可能还希望查看UNUserNotificationCenterDelegate以便更好地处理推送通知。 https://docs.microsoft.com/en-us/xamarin/ios/platform/user-notifications/enhanced-user-notifications?tabs=macos#handling-foreground-app-notifications