Alternative to UserNotificationCenterDelegate's willPresent when app is in background

南楼画角 提交于 2019-11-27 09:37:20

For iOS 10 local notifications your out of luck.

For iOS 10 remote notificationsregardless of user interaction you can receive callbacks using application(_:didReceiveRemoteNotification:fetchCompletionHandler:). (It's kind of confusing that they deprecated most notification related methods but not this one)


Callback for when app is in foreground and you're about to show the notification:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let content = notification.request.content
    // Process notification content

    completionHandler([.alert, .sound]) // Display notification as regular alert and play sound
}

Callback for when app is either in background or in foreground and user tapped on an action:

e.g. gives you a callback that user tapped on Save.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let actionIdentifier = response.actionIdentifier

    switch actionIdentifier {
    case UNNotificationDismissActionIdentifier: // Notification was dismissed by user
        // Do something
        completionHandler()
    case UNNotificationDefaultActionIdentifier: // App was opened from notification
        // Do something
        completionHandler()
    default:
        completionHandler()
    }
}

Callback for when app is either in background, foreground or (possibly) suspended state and a Push Notifications (Remote or silent notification) arrives:

Prior to iOS10 when you tapped on the notification the application(_:didReceiveRemoteNotification:fetchCompletionHandler:) would get called.

But since iOS 10 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) isn't called upon tapping. It's only called upon arrival of a remote Notification. (It get's called both in foreground and in background)


For pre iOS 10, you can just use the old didReceiveLocalNotification function and capture the arrival of any notification.

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