Created
December 14, 2022 12:19
-
-
Save madcato/355a5ca17ed1367bc315bd9835250954 to your computer and use it in GitHub Desktop.
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
// Asyncronous programming | |
import Foundation | |
// # Async-await samples | |
// ## Instead of using callbacks, ... | |
func getEmployeesJSON(url: URL, callback: @escaping ([Employee]) -> ())) { | |
URLSession.shared.dataTask(with: url), let response, response as? HTTPURLResponse, error == nil else { | |
if let let error = error { | |
print("Error downloading: \(error)") | |
return | |
} | |
if response.statusCode == 200 { | |
do { | |
let employees = try? JSONDecoder().decode([Employee].self, from: data) | |
callback(employees) | |
} catch { | |
print("Error decoding: \(error)") | |
} | |
} else { | |
print("Error downloading: \(response.statusCode)") | |
}.resume() | |
} | |
// ## ... we can use async-await | |
func getEmployeesJSON(url: URL) async throws -> [Employee] { | |
let (data, response) = try await URLSession.shared.data(from: url) | |
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { | |
throw URLError(.badServerResponse) | |
} | |
return try JSONDecoder().decode([Employee].self, from: data) | |
} | |
Task(priority: .background) { | |
do { | |
let employees = try await getEmployeesJSON(url: url) | |
print(employees) | |
} catch { | |
print("Error downloading: \(error)") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment