Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI – Publishing changes from background threads is not allowed

I am trying to create an app that creates random pictures when a button is clicked. The app is working fine but I see this message which I have never seen before."Publish changes from background threads is not allowed; make sure to publish values from the main thread.".
I am new to SwiftUI, help is appreciated.

import Foundation
import SwiftUI
  class ImageviewModel{
    var image: UIImage? = nil
    //let url = URL(string: "https://source.unsplash.com/random/600x600")!
    let url = URL(string: "https://picsum.photos/600/600")!
    func responseHandler(data: Data?, response: URLResponse?) ->
    UIImage?{
        guard let data = data,
              let image = UIImage(data: data),
              let response = response else {return nil}
        return image
    }
    func loadImageWithAsync() async throws -> UIImage?{
        do{
            let (data, response) = try await URLSession.shared.data(from: url,delegate: nil)
            return responseHandler(data: data, response: response)
        } catch{
            throw error
        }
    }
}
class ViewModel: ObservableObject{
    @Published var image: UIImage? = nil
    var loader = ImageviewModel()
    func fetchImage() async {
        let image = try? await loader.loadImageWithAsync()
        self.image = image
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to add the MainActor wrapper to the class to guarantee that updates are done on Main

@MainActor
class ViewModel: ObservableObject{
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading