如何在swift 3中获取通知授权状态?

时间:2017-09-27 21:47:20

标签: swift notifications authorization status

如何在iOS 11中查看UNUserNotificationCenter的当前授权状态?我一直在寻找一段时间并找到了一些代码,但它不是在swift 3中,有些功能在iOS 10中被弃用了。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:19)

好的,我找到了它:

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

代码:Kuba

答案 1 :(得分:3)

获取通知授权状态时,实际上可以有三种状态,即

  • 授权的
  • 拒绝
  • 非测定

检查这些内容的直接方法是使用.authorized.denied.nonDetermined作为UNAuthorizationStatus

中的枚举的切换案例
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
    print("Checking notification status")

    switch settings.authorizationStatus {
    case .authorized:
        print("authorized")

    case .denied:
        print("denied")

    case .notDetermined:
        print("notDetermined")

    }
}

UNAuthorizationStatus的说明可以在Apple的文档https://developer.apple.com/documentation/usernotifications/unauthorizationstatus

中找到