在我的应用中,我希望能够检查用户是否启用了通知。在iOS 10中,我使用委托中的检查来完成此操作。
现在不推荐使用此检查,我想更新它,但我无法弄清楚在iOS 11中使用什么。
弃用警告如下:
在iOS 10.0中不推荐使用currentUserNotificationSettings:使用 UserNotifications Framework的 - [UNUserNotificationCenter getNotificationSettingsWithCompletionHandler:]和 - [UNUserNotificationCenter getNotificationCategoriesWithCompletionHandler:]
我已尝试在此警告的帮助下更新代码,但我无法理解。
如果有人可以建议任何方式获得这样的支票,那将会有很大帮助。我在iOS 10中使用的代码如下所示,谢谢。
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == [] {
print("Notifications are NOT enabled")
} else {
print("Notifications are enabled")
}
答案 0 :(得分:23)
第1步:import UserNotifications
第2步:
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
// Notifications are allowed
}
else {
// Either denied or notDetermined
}
}
检查设置对象以获取更多信息。
答案 1 :(得分:7)
第一步: - 您必须将头文件添加为
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.
}
答案 2 :(得分:0)
我认为您可以致电UIApplication.shared.isRegisteredForRemoteNotifications