Last active
January 23, 2023 18:01
-
-
Save asimnajam/a732e8aa997a26f3ac51cb2fc6fb299a to your computer and use it in GitHub Desktop.
Usage of Async/Await in UIKit based iOS Application
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
// 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