在iOS10中关闭应用程序时如何响应本地通知?

Szy*_*n W 4 ios uilocalnotification swift ios10

当应用程序完全关闭(不在后台)时如何响应本地通知?

当应用程序在后台或前台运行时,一切正常。但是当应用程序关闭并且我试图回答通知时,只会"application didFinishLaunchingWithOptions"被调用,"userNotificationCenter didRecive response“没有回答。

我发现了这个问题(如何在应用程序关闭时处理 UNNotificationAction?)但在我的情况下,它既不适用于真实设备,也不适用于模拟器。

我还注意到,当我在应用程序关闭时响应通知时,该函数会"UNUserNotificationCenter.current().getDeliveredNotifications()"返回nil

ste*_*mit 6

对于iOS 9 及更低版本application(_:didFinishLaunchingWithOptions:)您将检查是否launchOptions包含localNotification: UIApplicationLaunchOptionsKey. 如果是这样,您就会知道该应用程序刚刚启动是因为本地通知(即用户点击了通知)。

对于iOS的10+,你必须注册UNUserNotificationCenterDelegateapplication(_:willFinishLaunchingWithOptions:)application(_:didFinishLaunchingWithOptions:)

您的委托人的职能:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void)
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序刚刚启动或只是在后台运行,则会被调用。这个新 API 的优点是只有一个地方可以处理本地通知操作。