Created
January 7, 2023 20:01
-
-
Save navsing/604c32968fcf188ddf67e9d5cde66d8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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