我的目标是检查UNUserNotificationCenter的授权状态(当应用程序再次激活/进入前台时),并根据信息打开或关闭UISwitch。
该函数工作并立即被触发,但UISwitch需要3-5秒才能更新。有没有更好的方法来更新它?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(checkNotificationSettings), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
func checkNotificationSettings() {
self.center.getNotificationSettings { (settings) in
switch settings.authorizationStatus {
case .authorized:
self.notificationSwitch.isOn = true
case .notDetermined, .denied:
self.notificationSwitch.isOn = false
}
}
}发布于 2017-05-02 12:29:21
getNotificationSettings基本上是异步请求通知设置,因此执行完成块需要一段时间。
上述方法的Apple文档还指出,完成块可以在后台线程上执行。但是,与UI交互的所有内容都必须在主线程上运行,否则会遇到类似于您在这种情况下遇到的问题。
您应该用DispatchQueue.main结束它,以便将与UI相关的工作中继到主队列,并且一切都应该按预期工作:
self.center.getNotificationSettings { settings in
DispatchQueue.main.async {
self.notificationSwitch.isOn = (settings.authorizationStatus == .authorized)
}
}https://stackoverflow.com/questions/43737680
复制相似问题