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

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

    @Rajat's answer is not enough.

    • isRegisteredForRemoteNotifications is that your app has connected to APNS and get device token, this can be for silent push notification
    • currentUserNotificationSettings is for user permissions, without this, there is no alert, banner or sound push notification delivered to the app

    Here is the check

    static var isPushNotificationEnabled: Bool {
      guard let settings = UIApplication.shared.currentUserNotificationSettings
        else {
          return false
      }
    
      return UIApplication.shared.isRegisteredForRemoteNotifications
        && !settings.types.isEmpty
    }
    

    For iOS 10, instead of checking for currentUserNotificationSettings, you should use UserNotifications framework

    center.getNotificationSettings(completionHandler: { settings in
      switch settings.authorizationStatus {
      case .authorized, .provisional:
        print("authorized")
      case .denied:
        print("denied")
      case .notDetermined:
        print("not determined, ask user for permission now")
      }
    })
    
    

    Push notification can be delivered to our apps in many ways, and we can ask for that

    UNUserNotificationCenter.current()
      .requestAuthorization(options: [.alert, .sound, .badge])
    

    User can go to Settings app and turn off any of those at any time, so it's best to check for that in the settings object

    open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding {
    
    
        open var authorizationStatus: UNAuthorizationStatus { get }
    
    
        open var soundSetting: UNNotificationSetting { get }
    
        open var badgeSetting: UNNotificationSetting { get }
    
        open var alertSetting: UNNotificationSetting { get }
    
    
        open var notificationCenterSetting: UNNotificationSetting { get }
    }
    

提交回复
热议问题