1. 程式人生 > >[Swift通天遁地]四、網路和執行緒-(4)使用Alamofire實現網路請求

[Swift通天遁地]四、網路和執行緒-(4)使用Alamofire實現網路請求

本文將演示如何使用第三方庫實現網路請求服務。

首先確保在專案中已經安裝了所需的第三方庫。

點選【Podfile】,檢視安裝配置檔案。

1 source 'https://github.com/CocoaPods/Specs.git'
2 platform :ios, '12.0'
3 use_frameworks!
4 
5 target ‘DemoApp’ do
6     pod 'Alamofire', '~> 4.0'
7 end

根據配置檔案中的相關配置,安裝第三方庫。

然後點選開啟【DemoApp.xcworkspace】專案檔案。

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

現在開始編寫程式碼,訪問一個網路介面,並在控制檯輸出返回的資訊。

 1 import UIKit
 2 //在當前的類檔案中,引入已經安裝的第三方類庫
 3 import Alamofire
 4 
 5 class ViewController: UIViewController {
 6 
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
 9         // Do any additional setup after loading the view, typically from a nib.
10 11 //呼叫網路操作庫的網路請求方法,並處理從伺服器返回的JSON資訊 12 Alamofire.request("https://httpbin.org/get").responseJSON { response in 13 14 //在控制檯輸出:返回的網路請求物件 15 print("response.request:\(response.request)") 16 //在控制檯輸出:網路返回物件 17 print("
response.response:\(response.response)") 18 //在控制檯輸出:由伺服器返回的資料 19 print("response.data:\(response.data)") 20 //在控制檯輸出:返回物件序列化後的結果 21 print("response.result:\(response.result)") 22 23 //輸出結果的值 24 if let JSON = response.result.value 25 { 26 print("JSON: \(JSON)") 27 } 28 } 29 } 30 31 override func didReceiveMemoryWarning() { 32 super.didReceiveMemoryWarning() 33 // Dispose of any resources that can be recreated. 34 } 35 }