Created
June 16, 2020 22:41
-
-
Save wb-softwares/aa3de1825d8fca8cad4337557e56128e to your computer and use it in GitHub Desktop.
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
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