更新从后台线程更改 UI 的变量 - SWIFTUI

Update a variable that changes the UI from background thread - SWIFTUI

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

我现在收到这个错误:

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
        }

尝试将 self.isLoaded = true 替换为

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

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

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