Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Last active April 30, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmlongco/a4a3de0a23c170e57853ca50ec6c05f8 to your computer and use it in GitHub Desktop.
Save hmlongco/a4a3de0a23c170e57853ca50ec6c05f8 to your computer and use it in GitHub Desktop.
Asynchronous API handling using GCD and Swift 5's new Result type
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