【问题标题】:Update a variable that changes the UI from background thread - SWIFTUI更新从后台线程更改 UI 的变量 - SWIFTUI
【发布时间】:2020-11-10 20:09:35
【问题描述】:

通知主线程后台线程操作完成的正确方法是什么?

我现在收到此错误:

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.

这是我进行后台队列操作的地方:

class ImageLoader: ObservableObject {
    //the thumbnail
    @Published var image: UIImage?

    //value to verify everything is loaded
    @Published var isLoaded = false
    
    
    private(set) var isLoading = false

    
    func load() {
        
        let dispatchQueue = DispatchQueue(label: "ThumbNailMaker", qos: .background)
        
        dispatchQueue.async {
            self.removeChar()
            self.createThumbnailOfVideoFromRemoteUrl()
            self.isLoaded = true     //<--------------------- Here the error appears
        }

【问题讨论】:

    标签: swift multithreading swiftui thread-safety apple-developer


    【解决方案1】:

    尝试将self.isLoaded = true替换为

    DispatchQueue.main.async { self.isLoaded = true }
    

    【讨论】:

      【解决方案2】:

      您可以简单地将该工作卸载回主线程:

      self.createThumbnailOfVideoFromRemoteUrl()
      DispatchQueue.main.async {
          self.isLoaded = true 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-20
        • 2023-03-28
        相关资源
        最近更新 更多