1. 程式人生 > >[Xcode10 實際操作]八、網路與多執行緒-(15)使用網址會話物件URLSession下載圖片並存儲在沙箱目錄中

[Xcode10 實際操作]八、網路與多執行緒-(15)使用網址會話物件URLSession下載圖片並存儲在沙箱目錄中

本文將演示如何通過網址會話物件URLSession下載圖片並存儲在沙箱目錄中。

網址會話物件URLSession具有在後臺上傳和下載、暫停和恢復網路操作、豐富的代理模式等優點。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4     
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
8 9 //建立一個網址物件,指定請求網路資料的網址。 10 let url = URL(string: "https://www.cnblogs.com/strengthen/images/logo.png") 11 //建立一個網路請求物件 12 let request:URLRequest = URLRequest(url: url!) 13 14 //網址會話URLSession在2013年釋出,蘋果對它的定位是作為舊的網路請求介面的替代者。 15 //這裡獲得網址會話的單例物件
16 let urlSession = URLSession.shared 17 18 //網址會話單例物件提供了三種類型的網路請求服務。 19 //1.資料任務 20 //2.上傳任務 21 //3.下載任務 22 //此處建立一個下載任務的網路請求 23 let downloadTask = urlSession.downloadTask(with: request, completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in
24 //建立一個異常捕捉語句,用來執行圖片下載後的移動操作 25 do 26 { 27 //獲得網路下載後,位於快取目錄的,圖片原始儲存路徑 28 let originalPath = location!.path 29 //並在控制檯列印輸出原始儲存路徑 30 print("Original location:\(originalPath)") 31 32 //建立一個字串,作為圖片儲存的目標位置 33 let targetPath:String = NSHomeDirectory() + "/Documents/logo.png" 34 35 //獲得檔案管理物件,它的主要功能包括: 36 //1.讀取檔案中的資料 37 //2.向檔案中寫入資料 38 //3.刪除或複製檔案 39 //4.移動檔案 40 //5.比較兩個檔案的內容 41 //6.測試檔案的存在性 42 let fileManager:FileManager = FileManager.default 43 //將下載後的圖片,從原始位置,移動到目標位置 44 try fileManager.moveItem(atPath: originalPath, toPath: targetPath) 45 //在控制檯列印輸出圖片儲存後的位置 46 print("new location:\(targetPath)") 47 } 48 catch 49 { 50 print("Network error.") 51 } 52 }) 53 54 //任務建立後,呼叫resume方法開始工作 55 downloadTask.resume() 56 } 57 58 override func didReceiveMemoryWarning() { 59 super.didReceiveMemoryWarning() 60 // Dispose of any resources that can be recreated. 61 } 62 }