Answer the question
In order to leave comments, you need to log in
How to work with the data received in the closure after exiting it?
Here is a piece of code below
func getData() {
let url = URL("...url...")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
let root = try? JSONDecoder().decode(Root.self, from: data)
print(root?.results[0])
}.resume()
}
Answer the question
In order to leave comments, you need to log in
1) use delegates
2) use completions that were passed to the getData method and then used inside the closure:
func getData(completionHandler: (data: MyData?) -> Void) {
let url = URL("...url...")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
let root = try? JSONDecoder().decode(Root.self, from: data)
print(root?.results[0])
completionHandler(root?.results[0])
}.resume()
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question