Skip to content

Instantly share code, notes, and snippets.

@asimnajam
Last active January 23, 2023 18:01
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 asimnajam/a732e8aa997a26f3ac51cb2fc6fb299a to your computer and use it in GitHub Desktop.
Save asimnajam/a732e8aa997a26f3ac51cb2fc6fb299a to your computer and use it in GitHub Desktop.
Usage of Async/Await in UIKit based iOS Application
// Referenaces
// https://developer.apple.com/videos/play/wwdc2021/10095/
// https://swiftly.dev/async-await
// https://www.avanderlee.com/swift/async-await/
// https://swiftsenpai.com/swift/async-await-network-requests/
enum CustomError: Error {
case invalidRequest
case unsupportedImage
}
final class Downloader {
static let shared: Downloader = Downloader()
private var dataTasks: Set<URLSessionDataTask> = Set<URLSessionDataTask>()
private let session = URLSession.shared
private var imageCache = NSCache<NSURL, UIImage>()
func downloadImg(url: URL) async throws -> UIImage {
let (data, response) = try await session.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
throw CustomError.invalidRequest
}
guard let image = UIImage(data: data) else {
throw CustomError.unsupportedImage
}
return image
}
}
class ViewModel {
func downloadImg() async -> UIImage? {
guard let urlString = currentQuestion.questionImageUrl,
isValidUrl(url: urlString),
let url = URL(string: urlString)
else {
return nil
}
do {
return try await imageDownloader.downloadImg(url: url)
} catch {
return nil
}
}
}
class ViewController {
var image: UIImage?
func fetchAndShowImage() {
Task {
image = viewModel.downloadImg()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment