Skip to content

Instantly share code, notes, and snippets.

@wb-softwares
Created June 16, 2020 22:41
Show Gist options
  • Save wb-softwares/aa3de1825d8fca8cad4337557e56128e to your computer and use it in GitHub Desktop.
Save wb-softwares/aa3de1825d8fca8cad4337557e56128e to your computer and use it in GitHub Desktop.
import Combine
import SwiftUI
struct ImageViewController: View {
@ObservedObject var url: LoadUrlImage
init(imageUrl: String) {
url = LoadUrlImage(imageURL: imageUrl)
}
var body: some View {
Image(uiImage: UIImage(data: self.url.data) ?? UIImage())
.resizable()
.clipped()
}
}
class LoadUrlImage: ObservableObject {
@Published var data = Data()
init(imageURL: String) {
let cache = URLCache.shared
let request = URLRequest(url: URL(string: imageURL)!, cachePolicy: URLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 60.0)
if let data = cache.cachedResponse(for: request)?.data {
self.data = data
} else {
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data, let response = response {
let cachedData = CachedURLResponse(response: response, data: data)
cache.storeCachedResponse(cachedData, for: request)
DispatchQueue.main.async {
self.data = data
}
}
}).resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment