How to respond to local notification when app is closed in iOS10?

余生颓废 提交于 2019-12-06 07:30:08

问题


How to respond to local notification when app is completly closed (not in background)?

When the app is running in the background or foreground everything works fine. But when the app is closed and I'm trying to answer to a notification, only "application didFinishLaunchingWithOptions" gets called, "userNotificationCenter didRecive response" isn't answering.

I found this question (How to handle UNNotificationAction when app is closed?) but in my case it doesn't work neither at a real device nor in a simulator.

I also noticed that the function "UNUserNotificationCenter.current().getDeliveredNotifications()" returns nil when I'm responding to a notification while app is closed.


回答1:


For iOS 9 and lower in application(_:didFinishLaunchingWithOptions:) you would check if launchOptions contains localNotification: UIApplicationLaunchOptionsKey. If so you would know that the app just freshly started because of local notification (i.e. user clicked on notification).

For iOS 10+ you must register your UNUserNotificationCenterDelegate in application(_:willFinishLaunchingWithOptions:) or application(_:didFinishLaunchingWithOptions:).

Your delegate's function:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void)

will be called if your app freshly started or it was just sitting in the background. The advantage of this new API is that there is only one place to handle local notification actions.



来源:https://stackoverflow.com/questions/40652431/how-to-respond-to-local-notification-when-app-is-closed-in-ios10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!