Completion with JSON

(Swift, macOS, Storyboards)

I can read a JSON from an URL. I would like to know when I can access the information. To be able to go from one function after the other. It seems that "completion" does not work with JSON? or perhaps I am doing something wrong?

I give a simplified example: I try to get the JSON information in func first() and then do something with that information in func second()

    var result2 = "empty"
    func first(completion: ()->()) {
        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        URLSession.shared.dataTask(with: url) { data, _, _ in
            if let data = data {
                let result = try? JSONDecoder().decode([User].self, from: data)
                self.result2 = result![0].name
            }
        }.resume()
        completion()
    }

    func second() {
        //do something after first()
        print (result2)
    }

    @IBAction func button1(_ sender: NSButton) {
        first {
          second()
        }
    }
Answered by OOPer in 687189022

You are putting completion() at the wrong place:

    func first(completion: @escaping ()->()) { //<-
        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        URLSession.shared.dataTask(with: url) { data, _, _ in
            if let data = data {
                let result = try? JSONDecoder().decode([User].self, from: data)
                self.result2 = result![0].name
                completion() //<- here
            }
        }.resume()
        //completion() //<- Not here
    }

Does the code compile ?

you call first() without completion label.

and you should pass the func, not its result.

try

first(completion: second  )
Accepted Answer

You are putting completion() at the wrong place:

    func first(completion: @escaping ()->()) { //<-
        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        URLSession.shared.dataTask(with: url) { data, _, _ in
            if let data = data {
                let result = try? JSONDecoder().decode([User].self, from: data)
                self.result2 = result![0].name
                completion() //<- here
            }
        }.resume()
        //completion() //<- Not here
    }
Completion with JSON
 
 
Q