检查Swift中推送通知的用户设置

我在我的应用中有推送通知。 每当应用程序启动时,我都想检查用户是否为我的应用程序启用了推送通知。

我是这样做的:

let notificationType = UIApplication.sharedApplication().currentUserNotificationSettings()!.types if notificationType == UIUserNotificationType.None { print("OFF") } else { print("ON") } 

如果用户禁用推送通知,有没有办法从我的应用程序激活此function?

或者有没有其他方法可以将用户发送到推送通知设置(设置 – 通知 – AppName)?

无法从应用程序更改设置。 但您可以使用此代码将用户引导至特定于应用程序的系统设置。

 extension UIApplication { class func openAppSettings() { UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } } 

针对Swift 3.0进行了更新

 extension UIApplication { class func openAppSettings() { UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } } 

适用于iOS 10或更高版本

检查是否已为您的应用启用推送通知已大幅改变Swift 3.如果您使用的是Swift 3,请使用此代替上述示例。

  let center = UNUserNotificationCenter.current() center.getNotificationSettings { (settings) in if(settings.authorizationStatus == .authorized) { print("Push authorized") } else { print("Push not authorized") } } 

以下是Apple有关如何进一步优化支票的文档: https : //developer.apple.com/reference/usernotifications/unnotificationsettings/1648391-authorizationstatus

这是Swift 3版本,您可以在其中检查是启用还是禁用通知。

 let notificationType = UIApplication.shared.currentUserNotificationSettings?.types if notificationType?.rawValue == 0 { print("Disabled") } else { print("Enabled") } 

斯威夫特4salabaha的回答

 extension UIApplication { class func openAppSettings() { UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: {enabled in // ... handle if enabled }) } 

简答:不,如果用户拒绝了您的推送通知请求,您无法再次询问它们,您应该将它们指向设置页面,您可以通过提醒告知他们步骤和两个选项“确定”和“转到设置“,这是您使用Roman代码的地方。

答案很长:你应该只在需要AND的时候询问用户推送通知,如果你要问它有助于前面有一个小视图解释为什么你想要/需要发送推送通知,这是一篇很棒的TechCrunch文章这将有助于您更好地保留/接受用户 – http://techcrunch.com/2014/04/04/the-right-way-to-ask-users-for-ios-permissions/