简体   繁体   中英

Receiving @Published on main thread

I have the following code giving me the following error message:

  class Variables: ObservableObject {
    @Published var isNotificationsEnabled: Bool = false
  }

  @EnvironmentObject var v: Variables

  func notificationsEnabled() {
    let current = UNUserNotificationCenter.current()

    current.getNotificationSettings(completionHandler: { (settings) in
        if settings.authorizationStatus == .notDetermined {
          v.isNotificationsEnabled = false
        } else if settings.authorizationStatus == .denied {
            // Notification permission was previously denied, go to settings & privacy to re-enable
          v.isNotificationsEnabled = false
        } else if settings.authorizationStatus == .authorized {
            // Notification permission was already granted
          v.isNotificationsEnabled = true
        }
    })
  }
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.

What can I do to fix this? I can't change the published variable

Wrap the if in a DispatchQueue.main.async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM