[问题] URLSession即便没网络还是可以拿到资料

楼主: JGC18 (JGC)   2017-09-10 16:20:02
各位前辈好, 小弟目前正在自学写ios app
功能是在viewDidLoad()去网络上面抓一张图显示到imageview这样
查到网络上的做法是用URLSession去拿资料
第一次跑起app顺利加载图片
但是当我把手机网络全部切断, 重新打开app, 居然还可以载到图片@@
response 的 data居然都有值
是不是有什么暂存的地方存了这张图片呢?
或是该用什么关键字去解决这样的情况, 请麻烦给我一些意见
下面是我简单的测试程式
storyboard上面只有一个ImageView
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let testAddress="http://az616578.vo.msecnd.net/files/2016/05/02/635977562108560005-679443365_kobe.jpg"
print("Begin of code")
if let checkedUrl = URL(string: testAddress) {
image1.contentMode = .scaleAspectFit
downloadImage(url: checkedUrl)
}
print("End of code. The image will continue downloading in the background and it will be loaded when it ends.")
}
//download image
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func downloadImage(url: URL) {
print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else {
print("Download error=\(error)")
return
}
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
self.image1.image = UIImage(data: data)
}
}
}
作者: bbkaf (bbkaf)   2017-09-10 18:26:00
https://imgur.com/a/PByIA要设定cachePolicy
作者: luckycan (罐头)   2017-09-10 20:42:00
推楼上,学习了
楼主: JGC18 (JGC)   2017-09-10 21:42:00
谢谢bbkaf,原来要设定这参数,可以了,谢谢

Links booklink

Contact Us: admin [ a t ] ucptt.com