There are 2 files:
1st - Network requests
2nd - ViewController, place where the result of getCities() -> Array<String> { ... }
should be called (at leasted could be checked with print
Using this to make a request:
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else { ...
}
The problem: The result of the request couldn't be accessed by UIViewController
until the finish of the request. The list
of UIViewController
is initiated too early.
P.S: Already tried
semaphore
and
group
but as for me, it works only for the same class/file.
Don't ask, tell
Use a completion handler to notify when the data are available. No semaphore, no group.
func getCities(completion: @escaping ([String]) -> Void) { ... }
and
getCities { [weak self] cities in
self?.list = cities
print(cities)
// do other stuff with received cities
}