第一步:
您必须将头文件添加为
import UserNotifications
我使用checkpushNotification方法来检查用户是否启用通知。使用从 AppDelegate 类的 didFinishLaunchingWithOptions 调用此方法。希望对你有帮助,有问题可以在下方评论。
最后一步:
func checkPushNotification(){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in
switch setttings.authorizationStatus{
case .authorized:
print("enabled notification setting")
case .denied:
print("setting has been disabled")
case .notDetermined:
print("something vital went wrong here")
}
}
} else {
let isNotificationEnabled = UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert)
if isNotificationEnabled{
print("enabled notification setting")
}else{
print("setting has been disabled")
}
}
}
如果您想要启用或禁用某些布尔输出,那么您应该实现完成处理程序来解决它。
func checkPushNotification(checkNotificationStatus isEnable : ((Bool)->())? = nil){
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in
switch setttings.authorizationStatus{
case .authorized:
print("enabled notification setting")
isEnable?(true)
case .denied:
print("setting has been disabled")
isEnable?(false)
case .notDetermined:
print("something vital went wrong here")
isEnable?(false)
}
}
} else {
let isNotificationEnabled = UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert)
if isNotificationEnabled == true{
print("enabled notification setting")
isEnable?(true)
}else{
print("setting has been disabled")
isEnable?(false)
}
}
}
并将这个简单称为
self.checkPushNotification { (isEnable) in
print(isEnable)
// you know notification status.
}