-
-
Save classx/981924d06f31b3a9916a5e24166ea9e4 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, 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