如何打开和关闭 iOS 中的通知?

How to turn on and off notifications in iOS?

我正在尝试在 iOS 11 应用程序中实现设置屏幕,我需要一个 UISwitch 来控制用户通知。当设置为关闭时,我想放弃通知权限,当设置为打开时,我想请求权限(标准对话框要求用户允许发送她的通知)。

为了请求许可,我找到了以下代码:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization.
}

但是,如果我在系统设置中关闭该应用程序的通知,此代码不会弹出带有请求的对话框,它只是 returns 在 granted 中为 false。

我找不到任何关于如何放弃权限的信息。

关于如何解决问题的任何提示?有没有可能,或者 Apple 认为这个任务应该只留给系统设置?

In iOS Turn on/off permission push notification appears only one time. So in order to achieve that you need to do some tweak like you can check first whether your notification is enabled or not.

func pushEnabledAtOSLevel() -> Bool {
 guard let currentSettings = UIApplication.shared.currentUserNotificationSettings?.types else { return false }
 return currentSettings.rawValue != 0
}

After that you can create your customize popup with TurnON/Off button and navigate to System setting page where user can enable that option accordingly

if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
    UIApplication.shared.openURL(appSettings as URL)
}

对于 iOS 10.0 及更高版本

  UNUserNotificationCenter.current().getNotificationSettings { (settings) in
        if settings.authorizationStatus == .authorized {
            // Notifications are allowed
        }
        else {
            // Either denied or notDetermined

            let alertController = UIAlertController(title: nil, message: "Do you want to change notifications settings?", preferredStyle: .alert)

            let action1 = UIAlertAction(title: "Settings", style: .default) { (action:UIAlertAction) in
                if let appSettings = NSURL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(appSettings as URL, options: [:], completionHandler: nil)
                }
            }

            let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
            }

            alertController.addAction(action1)
            alertController.addAction(action2)
            self.present(alertController, animated: true, completion: nil)
        }
    }