gpt4 book ai didi

ios - 查看本地通知的授权状态

转载 作者:行者123 更新时间:2023-11-30 12:20:52 26 4
gpt4 key购买 nike

我在我的应用程序中使用本地通知,在向用户呈现新的通知屏幕之前,我想先检查授权状态。我使用 shouldPerformSegue(identifier:, sender:) -> Bool 方法,这样如果通知未经用户授权,则不会呈现用户配置和保存新通知的场景:

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "AddReminder" {
// Check to see if notifications are authorised for this app by the user
let isAuthorised = NotificationsManager.checkAuthorization()
if isAuthorised {
print(isAuthorised)
return true
}
else {
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
(action: UIAlertAction) in
}

let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsURL) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: { (success) in
print("Settings opened: \(success)")
})
}
}
alert.addAction(cancelAction)
alert.addAction(settingsAction)

present(alert, animated: true, completion: nil)

print(isAuthorised)
return false
}
}

// By default, transition
return true
}

这是我用于授权检查的方法:

static func checkAuthorization() -> Bool {
// var isAuthorised: Bool
var isAuthorised = true
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }

})
print("Reached .notDetermined stage")
case .authorized:
isAuthorised = true
case .denied:
isAuthorised = false
}

}

//print("Last statement reached before the check itself")
return isAuthorised
}

我认为上述函数中的最后一条语句(返回 isAuthorized)在 UNUserNotificationCenter.current().getNotificationSettings{} 的主体执行之前返回,因此它总是返回 isAuthorized 在最开始处配置的内容方法。

问题:您能否建议我如何使用更好的方法检查授权,因为我的方法甚至不起作用。

这只是我的第一个IOS应用程序,所以我对IOS开发还比较陌生;任何帮助将不胜感激。

最佳答案

如果有人遇到类似问题,请不要使用 getNotificationsSettings(){} 方法,该方法将在返回封闭方法后计算;我们可以使用不同的方法,即获取 currentUserNotificationSettings,这是我们应用程序的通知设置。然后检查当前设置是否包含.aler、.sound等。如果答案是YES,那么我们可以确定应用程序已启用通知。

关于ios - 查看本地通知的授权状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44808362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com