1. 程式人生 > >[Xcode10 實際操作]八、網路與多執行緒-(9)使用非同步Get方式獲取網頁原始碼

[Xcode10 實際操作]八、網路與多執行緒-(9)使用非同步Get方式獲取網頁原始碼

本文將演示如何通過Get請求方式,非同步獲取網頁原始碼。

非同步請求與同步請求相比,不會阻塞程式的主執行緒,而會建立一個新的執行緒。

在專案導航區,開啟檢視控制器的程式碼檔案【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/") 11 12 //建立一個網路請求物件,引數說明: 13 //1.代表請求訪問的路徑 14 //2.代表網路請求的快取協議 15 //3.代表網路請求的超時時間 16 let request = URLRequest.init(url: url!, 17 cachePolicy: .useProtocolCachePolicy,
18 timeoutInterval: 30) 19 20 //網址會話URLSession在2013年釋出,蘋果對它的定位是作為舊的網路請求介面的替代者。 21 //這裡獲得網址會話的單例物件 22 let session = URLSession.shared 23 //所有網路請求工作,都是通過網址會話任務物件來完成的。 24 //可以使用閉包、代理或者兩者混合的方式,來建立網路請求任務。 25 //建立一個網路請求任務,根據指定的網址請求物件,獲取介面的內容, 26 //
並在完成時通過閉包語句,處理伺服器返回的資料 27 let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in 28 //如果出現網路請求錯誤, 29 if error != nil{ 30 //則在控制檯列印輸出錯誤程式碼和錯誤資訊 31 print(error.debugDescription) 32 }else{ 33 //將網路返回的資料物件,根據指定的編碼方式,轉換為字串 34 let result = String(data: data!, encoding: String.Encoding.utf8)、 35 //在控制檯輸出字串的內容 36 print(result ?? "") 37 } 38 }) 39 40 //任務建立後,呼叫resume方法開始工作。 41 task.resume() 42 } 43 44 override func didReceiveMemoryWarning() { 45 super.didReceiveMemoryWarning() 46 // Dispose of any resources that can be recreated. 47 } 48 }