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

Mil*_*sáľ 2 ios swift usernotifications unusernotificationcenter

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

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

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

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

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

有关如何解决问题的任何提示?甚至有可能吗,或者苹果是否认为这个任务应该只留给系统设置?

Hus*_*bir 5

在 iOS 中打开/关闭权限推送通知只出现一次。因此,为了实现这一点,您需要进行一些调整,例如您可以先检查您的通知是否已启用。

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

之后,您可以使用打开/关闭按钮创建自定义弹出窗口并导航到系统设置页面,用户可以在其中相应地启用该选项

if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
    UIApplication.shared.openURL(appSettings as URL)
}
Run Code Online (Sandbox Code Playgroud)