Search Your Question

How to switch from background queue to main queue?

If you're on a background thread and want to execute code on the main thread, you need to call async() again. However, this time, you do it on DispatchQueue.main, which is the main thread, rather than one of the global quality of service queues.


DispatchQueue.global(qos: .userInitiated).async {

    if let url = URL(string: urlString) {

        if let data = try? Data(contentsOf: url) {

            self.parse(json: data)

            return

        }

    }

    self.showError()

}


func showError() {

    DispatchQueue.main.async {

        let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .alert)

        ac.addAction(UIAlertAction(title: "OK", style: .default))

        self.present(ac, animated: true)

    }

}


Sof here, If I want to work with UI-related stuff, I must switch queue to main. So to execute that code under  DispatchQueue.main.async { } block.

No comments:

Post a Comment

Thanks