Launched in Swift 5.5 (iOS 15, macOS 12), we might now use the async–await sample:
func fetchGenres() async throws -> [Genre] {
…
let (information, _) = attempt await URLSession.shared.dataTask(for: request)
return attempt JSONDecoder().decode([Genre].self, from: information)
}
And we might name it like:
let genres = attempt await fetchGenres()
The async–await syntax is way extra concise and pure than the standard completion handler sample outlined in my unique reply, under.
For extra info, see Meet async/await in Swift.
The historic sample is to make use of completion handlers closure.
For instance, we might usually use End result:
func fetchGenres(completion: @escaping (End result<[Genre], Error>) -> Void) {
...
URLSession.shared.dataTask(with: request) { information, _, error in
if let error = error {
DispatchQueue.most important.async {
completion(.failure(error))
}
return
}
// parse response right here
let outcomes = ...
DispatchQueue.most important.async {
completion(.success(outcomes))
}
}.resume()
}
And also you’d name it like so:
fetchGenres { leads to
change outcomes {
case .failure(let error):
print(error.localizedDescription)
case .success(let genres):
// use `genres` right here, e.g. replace mannequin and UI
}
}
// however don’t attempt to use `genres` right here, because the above runs asynchronously
Be aware, above I’m dispatching the completion handler again to the primary queue to simplify mannequin and UI updates. Some builders take exception to this apply and both use no matter queue URLSession used or use their very own queue (requiring the caller to manually synchronize the outcomes themselves).
However that’s not materials right here. The important thing situation is using completion handler to specify the block of code to be run when the asynchronous request is completed.
Be aware, above I retired using NSArray (we don’t use these bridged Goal-C varieties any extra). I assume that we had a Style kind and we presumably used JSONDecoder, relatively than JSONSerialization, to decode it. However this query didn’t have sufficient details about the underlying JSON to get into the small print right here, so I omitted that to keep away from clouding the core situation, using closures as completion handlers.
