Hansy
Hansy

Reputation: 73

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

What is the correct way to notify the main thread, that the background-thread operations are finished?

I get this error now:

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.

Here is where i make the background-queue-operations:

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
        }

Upvotes: 3

Views: 3330

Answers (2)

Samuel-IH
Samuel-IH

Reputation: 813

You could simply offload that work back to the main thread:

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

Upvotes: 2

Stephan Boner
Stephan Boner

Reputation: 753

Try to replace the self.isLoaded = true with

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

Upvotes: 4

Related Questions