Dispatch Queue - main and in background situation with var

Hello!


I want to verify a property of a tagBarItem but the navigation controller needs to be accessed on the main queue.


However, I have a blocking call that I want to be processed in the background.


The problem is that in line 15 when I access the value of petitionString it is empty.


What am I doing wrong?


performSelector(inBackground: #selector(fetchJSON), with: nil)


@objc func fetchJSON() {
        
        var petitionURLString: String = ""
        
        DispatchQueue.main.async {
            [weak self] in
            if self?.navigationController?.tabBarItem.tag == 0 {
                petitionURLString = "https://www.hackingwithswift.com/samples/petitions-1.json"
            }
            else {
                petitionURLString = "https://www.hackingwithswift.com/samples/petitions-2.json"
            }
        }
        
        if let url = URL(string: petitionURLString) {
            if let data = try? Data(contentsOf: url) { //Este método é chamado de blocking call bloqueia a execução de código até todos os dados estarem descarregados.
                //É seguro fazer parsing dos dados mas como pode dar erro usamos try?
                parseData(json: data)
                return
            }
        }

        showError()
    }

Replies

You have to think of the order of execution, when you use asynchronous patterns. The order of execution here is:


a. Line 3

b. Line 5, which causes line 7-12 to be executed "later", continuing on for "now" with…

c. lines 15-23

d. (later) lines 7-12


What you'll need to do, basically, is move lines 15-23 inside a closure that's dispatch back to a background queue/thread after the stuff on th main thread is done.