我有一个开关按钮,可以触发通知警报。我能够实现请求通知权限(用户第一次触发开关时),我还能够实现当用户再次单击开关按钮时让用户打开应用程序的通知设置(如果用户拒绝第一次)要求)。但我在如何将通知打开信息返回到应用程序时遇到问题。
在此阶段,如何检测应用程序的通知设置已打开并将开关按钮显示为“打开”?
我尝试覆盖 func viewWillAppear (这不起作用,因为当您从“设置”返回应用程序时,视图控制器永远不会再次调用/重新加载。) 我也在AppDelegate、applicationWillEnterForeground和applicationDidBecomeActive中尝试过,都不起作用。
我希望这是有道理的。谢谢您的任何建议。
将 UserNotifications 导入到您的 ViewController 中
import UserNotifications
创建一个方法来检查当前通知状态
private func hasNotificationPermission(completion: @escaping (Bool) -> Void) {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
completion(settings.authorizationStatus == .authorized)
}
}
添加观察者以检测应用程序何时激活
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.UIApplicationDidBecomeActive, object: nil)
}
从后台返回时检查通知状态并更新您的 UI
@objc func appBecomeActive() {
if hasNotificationPermission {
// Notifications are enabled
} else {
// Notifications are not enabled
}
}
对于 SwiftUI 应用程序,您可以将以下修饰符附加到视图:
.onReceive(
NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)
) { _ in
Task {
let settings = await UNUserNotificationCenter.current().notificationSettings()
let notificationsAreEnabled = settings.authorizationStatus == .authorized
}
}