Last active
April 30, 2019 14:55
-
-
Save hmlongco/a4a3de0a23c170e57853ca50ec6c05f8 to your computer and use it in GitHub Desktop.
Asynchronous API handling using GCD and Swift 5's new Result type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func load() { | |
DispatchQueue.global(qos: .utility).async { | |
let result = self.makeAPICall() | |
DispatchQueue.main.async { | |
switch result { | |
case let .success(data): | |
print(data) | |
case let .failure(error): | |
print(error) | |
} | |
} | |
} | |
} | |
func makeAPICall() -> Result<String?, NWError> { | |
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { | |
return .failure(.notFound) | |
} | |
var result: Result<String?, NWError>! | |
let semaphore = DispatchSemaphore(value: 0) | |
URLSession.shared.dataTask(with: url) { (data, _, _) in | |
if let data = data { | |
result = .success(String(data: data, encoding: .utf8)) | |
} else { | |
result = .failure(.failed) | |
} | |
semaphore.signal() | |
}.resume() | |
_ = semaphore.wait(wallTimeout: .distantFuture) | |
return result | |
} | |
enum NWError: Error { | |
case notFound | |
case failed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment