訪問 Web 服務



在我們的應用中,我們可能需要連線到 API,從該 API 中檢索資料並在我們的應用中使用。

首先,我們需要提供資料的 URL。

api.openweathermap.org/data/2.5/forecast?id=524901&APPID=1111111111

然後,如果服務不是 https 服務,我們需要新增傳輸層安全例外,以允許我們的應用程式與 Web 服務通訊。我們將在 info.plist 檔案中進行這些更改。

最後,我們將建立一個 URLSession 來建立網路請求。

let urlString = URL(string: "your URL")  // Making the URL  
if let url = urlString {   
   let task = URLSession.shared.dataTask(with: url) { 
      (data, response, error) in // Creating the URL Session. 
      if error != nil {  
         // Checking if error exist. 
         print(error) 
      } else { 
         if let usableData = data { 
            // Checking if data exist. 
            print(usableData)   
            // printing Data. 
         } 
      } 
   }
}	
task.resume() 

這就是你可以使用 URL 會話在應用中使用 Web 服務的方式。

Alamofire

Alamofire 是一個用 Swift 編寫 HTTP 網路庫。它可用於進行 URL 請求、釋出資料、接收資料、上載檔案、資料、認證、驗證等。

要安裝 Aalmofire,你可以透過 GitHub 訪問 Alamofire 官網並閱讀其安裝指南

在 Alamofire 中提出請求

要在 Alamofire 中發出請求,我們應該使用以下命令。

Import Alamofire 
Alamofire.request("url");

響應處理

以下命令用於響應處理。

Alamofire.request("url").responseJSON {  
   response in      
   print(response.request)   
   // original URL request     
   print(response.response)  
   // HTTP URL response      
   print(response.data)      
   // server data      
   print(response.result)    
   // result of response serialization       
   if let JSON = response.result.value {          
      print("JSON: \(JSON)")   
   } 
}  

響應驗證

以下命令用於響應處理。

Alamofire.request("https://httpbin.org/get").validate().responseJSON {  
   response in      
   switch response.result {      
      case .success:         
      print("Validation Successful")      
      case .failure(let error):      
      print(error)      
   } 
}

這些是使用 URL 會話和 Alamofire 發出 URL 請求的基礎知識。有關更高階的 Alamofire,請訪問 Alamofire 文件,你可以詳細閱讀有關它的內容。

廣告
© . All rights reserved.