Member-only story
Swift 5: Async/Await Timeouts with Result and GCD
Or what to do when you get tired of waiting.
In Swift 5: How to do Async/Await with Result and GCD, I demonstrated how to simulate async/await with multiple API calls using Swift 5’s new Result type and Grand Central Dispatch (GCD) Semaphores.
However, there’s one gotcha still in the code I presented: It assumes that the API call will complete or eventually timeout.
But what happens if the call never completes? Your API request never times out? Or if you simply get tired of waiting?
We’re waiting, we’re waiting…
In our original makeAPICall example, we call semaphore.wait(wallTimeout: .distantFuture) to block the current thread until our callback executes and returns our data, or an error.
func makeAPICall() -> Result<String?, NetworkError> {
let path = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: path) else {
return .failure(.url)
} var result: Result<String?, NetworkError>!
let semaphore = DispatchSemaphore(value: 0) URLSession.shared.dataTask(with: url) { (data, _, _) in
if let data = data {
result = .success(String(data: data, encoding: .utf8))…