各位前輩好, 小弟目前正在自學寫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)
}
}
}