如何检测“清除”通知

问题描述 投票:1回答:1

如果从用户通知到达通知中心的时间超过一分钟,则有一个“清除”选项可以立即从通知中心解除一个或多个通知。

iOS操作系统如何通知用户点击“清除”以同时关闭多个通知?

ios swift apple-push-notifications
1个回答
2
投票

它可以从iOS 10及更高版本实现自定义通知,您需要使用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
    }

}

从appdelegate的didFinishLaunching方法调用registerForRemoteNotificaiton方法。

然后,您需要在appdelegate中实现UNUserNotificationCenterDelegate。

然后你会得到清楚的(这里我们在动作名称中添加了“Dismiss”)

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

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

    }

    completionHandler()
}

查找更多信息here

© www.soinside.com 2019 - 2024. All rights reserved.