【问题标题】:How can I check if a specific type of local notification is enabled?如何检查是否启用了特定类型的本地通知?
【发布时间】:2020-05-11 00:59:35
【问题描述】:

如果我使用下面的代码请求对警报和声音的本地通知进行授权,则用户可以在授予授权后进入设置关闭横幅和声音。授权仍然存在,但不会有发送通知的方法。如何检查是否启用了特定类型的通知(例如警报)?

@objc func registerLocal() {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        if granted {
            self.notificationsAuth = true
        } else {
            self.notificationsAuth = false
        }
        self.notificationAuthUndertermined = false
    }
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    对于 iOS 10.0 及更高版本:

    UNUserNotificationCenter.current().getNotificationSettings { (settings) in
    
            // also available for badgeSetting, soundSetting, authorization status and ...
    
            switch settings.alertSetting {
            case .notSupported:
                // Do stuff
                break
    
            case .disabled:
                // Do stuff
                break
    
            case .enabled:
                // Do stuff
                break
            }
    }
    

    【讨论】:

      【解决方案2】:

      我们可以使用下面的代码验证alertSettingsoundSettingbadgeSetting是否启用,

       func getNotificationSettings() {
      UNUserNotificationCenter.current().getNotificationSettings { settings in
          print("Notification settings: \(settings)")
      
          let isAlertEnabled = settings.alertSetting
          let isSoundEnable = settings.soundSetting
          let isbadgeEnabled = settings.badgeSetting
      
          if(isAlertEnabled == .enabled && isSoundEnable == .enabled && isbadgeEnabled == .enabled){
            print("Alert, Sound and Badges are enabled.")
          }else{
              //Different action
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-16
        • 2014-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多