Alternative to UserNotificationCenterDelegate's willPresent when app is in background

前端 未结 1 1064
旧时难觅i
旧时难觅i 2020-12-02 01:30

I am trying to figure out whether I can accomplish my goal through Local Notifications, or whether I need to switch to Remote Notifications.

I\'m practicing iOS 10

相关标签:
1条回答
  • 2020-12-02 01:39

    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.

    0 讨论(0)
提交回复
热议问题