I am downloading images from a website using the code below which caches images. Do I need to save images in the application directory so that they can be saved forever?
After running this code, I can turn on my device in airplane mode, restart it and open the application, and the images are still there. What bothers me. I thought caching was temporary? Where is this image stored and, most importantly, how long?
I read the Apple URL Programming Guide and it did not answer these questions.
func getImageFromWeb(_ urlString: String, closure: @escaping (UIImage?) -> Void) {
guard let url = URL(string: urlString) else {
return closure(nil)
}
let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
guard error == nil else {
print("error: \(String(describing: error))")
return closure(nil)
}
guard response != nil else {
print("no response")
return closure(nil)
}
guard data != nil else {
print("no data")
return closure(nil)
}
DispatchQueue.main.async {
closure(UIImage(data: data!))
}
}; task.resume()
}
Function call:
getImageFromWeb("http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") { (image) in
if let image = image {
}
}
Bobby source
share