当用户使用 UISwitch 禁用它时,如何暂时禁用所有本地通知?

How can I temporarily diable all local notifications when user disable it by using UISwitch?

我想在我的设置页面中使用 UISwich,如果用户关闭它,它将暂时禁用所有本地通知。

在swiftapplication.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil))中注册本地通知。

有没有取消注册本地通知的功能,就像用户在iOS的设置页面中关闭特定通知一样??

第一种方法

  1. 当用户更改开关的值时,可以将其状态存储在 NSUserDefaults 中。

  2. 当通过 application(_:didReceiveLocalNotification:)application:didReceiveRemoteNotification: 收到通知时,请检查上述状态变化,如果用户已关闭通知,则忽略它们。

第二种方法

使用unregisterForRemoteNotifications()

You should call this method in rare circumstances only, such as when a new version of the app removes support for all types of remote notifications. Users can temporarily prevent apps from receiving remote notifications through the Notifications section of the Settings app. Apps unregistered through this method can always re-register.

第三种方法

使用远程 通知时,您将使用服务器端代码将这些推送到 APNS。在这种情况下,当用户想要停止通知时,您可以设置一个标志服务器端告诉它不再将它们发送到 APNS。

确保导入 UIKit 和 UserNotifications 以下代码在swift3

func removeLocalNotifications() {

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: {requests -> () in
            print("\(requests.count) requests -------")
            for request in requests{
                let notifIdentifier: String = request.identifier as String
                print("notifIdentifier deleted: \(notifIdentifier)")
                UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notifIdentifier])
            }
        })
        UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {deliveredNotifications -> () in
            print("\(deliveredNotifications.count) Delivered notifications-------")
            for notification in deliveredNotifications{
                let notifIdentifier: String = notification.request.identifier as String
                print("notifIdentifier deleted: \(notifIdentifier)")
                UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notifIdentifier])
            }
        })
    } else { ///for iOS < 10
        let app: UIApplication = UIApplication.shared
        for oneEvent in app.scheduledLocalNotifications! {
            print("oneEvent Deleted ======================= \(oneEvent)")
            let notification = oneEvent as UILocalNotification
            app.cancelLocalNotification(notification)
        }
    }
}