import UIKit
enum NetworkError: Error {
case invalidServerResponse
case unsupportedImage
}
func fetchPhoto(url: URL) async throws -> UIImage {
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw NetworkError.invalidServerResponse
}
guard let image = UIImage(data: data) else {
throw NetworkError.unsupportedImage
}
return image
}
let photoURL = URL(string: "https://developer.apple.com/swift/images/swift-og.png")!
// using `async` here to test calling an `async/await` function since we cannot call it synchronously
// `async(priority:operation:)`: Runs the given nonthrowing operation asynchronously as part of a new top-level task on behalf of the current actor.
// Swift's new Concurrency Framework: https://developer.apple.com/documentation/swift/swift_standard_library/concurrency
async {
do {
let image = try await fetchPhoto(url: photoURL)
print(image)
} catch {
print(error)
}
}
// <UIImage:0x600003a8c6c0 anonymous {1200, 1200} renderingMode=automatic>

Github repo here.