Swift ios check if remote push notifications are enabled in ios9 and ios10

后端 未结 11 1321
悲哀的现实
悲哀的现实 2020-12-01 02:26

How can I check if the user has enabled remote notifications on ios 9 or ios 10?

If the user has not allowed or clicked No I want to toggle a message asking if they

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 03:16

    in iOS11, Swift 4...

     UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            if settings.authorizationStatus == .authorized {
                // Already authorized
            }
            else {
                // Either denied or notDetermined
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                    (granted, error) in
                      // add your own 
                    UNUserNotificationCenter.current().delegate = self
                    let alertController = UIAlertController(title: "Notification Alert", message: "please enable notifications", preferredStyle: .alert)
                    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                            return
                        }
                        if UIApplication.shared.canOpenURL(settingsUrl) {
                            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                            })
                        }
                    }
                    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
                    alertController.addAction(cancelAction)
                    alertController.addAction(settingsAction)
                    DispatchQueue.main.async {
                        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    
                    }
                }
            }
        }
    

提交回复
热议问题