How to detect “clear” notifications

2019-03-05 23:45发布

问题:

if more than a minute pass from the time a user notification arrived to notification center, there is a "clear" option to dismiss one or more notifications at once from notification center.

How the iOS OS notify that the user tapped on "clear" to dismiss several notifications together?

回答1:

its possible from iOS 10 and above with implementation of custom notification, you will need to work with UNNotificaitons

private func registerForRemoteNotificaiton(_ application: UIApplication) {
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {(granted, error) in
                if granted {
                    DispatchQueue.main.async(execute: {
                        UIApplication.shared.registerForRemoteNotifications()
                    })
                }
        })
        configureUserNotification()
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        // For iOS 10 data message (sent via FCM)
        Messaging.messaging().delegate = self as MessagingDelegate
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    // [END register_for_notifications]
}

private func configureUserNotification() {
    if #available(iOS 10.0, *) {
        let action = UNNotificationAction(identifier: UNNotificationDismissActionIdentifier, title: "Cancel", options: [])
        //let action1 = UNNotificationAction(identifier: "dismiss", title: "OK", options: [])
        let category = UNNotificationCategory(identifier: "myNotificationCategory", actions: [action], intentIdentifiers: [], options: .customDismissAction)
        UNUserNotificationCenter.current().setNotificationCategories([category])
    } else {
        // Fallback on earlier versions
    }

}

call registerForRemoteNotificaiton method from appdelegate's didFinishLaunching method.

Then you will need to implement UNUserNotificationCenterDelegate in appdelegate.

and then you will get the clear (here "Dismiss" as we added in action name)

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

    if response.actionIdentifier == UNNotificationDismissActionIdentifier {
        //user dismissed the notifcaiton:

    }

    completionHandler()
}

find more information here