Skip to content

Instantly share code, notes, and snippets.

Avatar

ali akhtar aliakhtar49

View GitHub Profile
View gist:4b4543a437869f5b6cd733c806043294
func downloadImageAndMetadata(imageNumber: Int) async throws -> DetailedImage {
return try await withCheckedThrowingContinuation({
(continuation: CheckedContinuation<DetailedImage, Error>) in
downloadImageAndMetadata(imageNumber: imageNumber) { image, error in
if let image = image {
continuation.resume(returning: image)
} else {
continuation.resume(throwing: error!)
}
}
View swift
let metadataUrl = URL(string: "https://www.andyibanez.com/fairesepages.github.io/tutorials/async-await/part1/\(imageNumber).json")!
let metadataTask = URLSession.shared.dataTask(with: metadataUrl) { data, response, error in
guard let data = data, let metadata = try? JSONDecoder().decode(ImageMetadata.self, from: data), (response as? HTTPURLResponse)?.statusCode == 200 else {
completionHandler(nil, ImageDownloadError.invalidMetadata)
return
}
let detailedImage = DetailedImage(image: image, metadata: metadata)
completionHandler(detailedImage, nil)
}
metadataTask.resume()
View gist:812f13d47966e485bd0d46f017a59af3
func downloadMetadata(for id: Int) async throws -> ImageMetadata {
let metadataUrl = URL(string: "https://www.andyibanez.com/fairesepages.github.io/tutorials/async-await/part1/\(id).json")!
let metadataRequest = URLRequest(url: metadataUrl)
let (data, metadataResponse) = try await URLSession.shared.data(for: metadataRequest)
guard (metadataResponse as? HTTPURLResponse)?.statusCode == 200 else {
throw ImageDownloadError.invalidMetadata
}
return try JSONDecoder().decode(ImageMetadata.self, from: data)
}