[問題] URLSession即便沒網路還是可以拿到資料

看板MacDev作者 (JGC)時間6年前 (2017/09/10 16:20), 編輯推噓2(202)
留言4則, 3人參與, 最新討論串1/1
各位前輩好, 小弟目前正在自學寫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) } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.182.116.114 ※ 文章網址: https://www.ptt.cc/bbs/MacDev/M.1505031605.A.DA6.html

09/10 18:26, , 1F

09/10 18:27, , 2F
要設定cachePolicy
09/10 18:27, 2F

09/10 20:42, , 3F
推樓上,學習了
09/10 20:42, 3F

09/10 21:42, , 4F
謝謝bbkaf,原來要設定這參數,可以了,謝謝
09/10 21:42, 4F
文章代碼(AID): #1PjFMrsc (MacDev)