应用程序启动后,布局更新较慢。

3
我的目标是在应用程序再次变为活动状态 / 进入前台时检查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
    }
  }
}
1个回答

3

getNotificationSettings 基本上是以异步方式请求通知设置,因此需要一些时间才能执行完成块。

上述方法的苹果文档还说,完成块可能在后台线程上执行。然而,凡与UI交互的内容必须在主线程上运行,否则您会遇到类似于您所遇到的问题。

您应该使用 DispatchQueue.main 将UI相关工作转发到主队列中,这样一切都应该按预期工作:

self.center.getNotificationSettings { settings in
  DispatchQueue.main.async { 
    self.notificationSwitch.isOn = (settings.authorizationStatus == .authorized)
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接