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

后端 未结 11 1255
悲哀的现实
悲哀的现实 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:11

    All answers above are almost correct BUT if you have push notifications enabled and all options disabled (alertSetting, lockScreenSetting etc.), authorizationStatus will be authorized and you won't receive any push notifications.

    The most appropriate way to find out if you user can receive remote notifications is to check all these setting values. You can achieve it using extensions.

    Note: This solution works for iOS 10+. If you support older versions, please read previous answers.

    extension UNNotificationSettings {
    
        func isAuthorized() -> Bool {
            guard authorizationStatus == .authorized else {
                return false
            }
    
            return alertSetting == .enabled ||
                soundSetting == .enabled ||
                badgeSetting == .enabled ||
                notificationCenterSetting == .enabled ||
                lockScreenSetting == .enabled
        }
    }
    
    extension UNUserNotificationCenter {
    
        func checkPushNotificationStatus(onAuthorized: @escaping () -> Void, onDenied: @escaping () -> Void) {
            getNotificationSettings { settings in
                DispatchQueue.main.async {
                    guard settings.isAuthorized() {
                        onDenied()
                        return
                    }
    
                    onAuthorized()
                }
            }
        }
    }
    

提交回复
热议问题