目錄:[Swift]Xcode實際操做html
本文將演示如何經過網址會話對象URLSession下載圖片並存儲在沙箱目錄中。swift
網址會話對象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 }