- 使用 Swift 2 進行 iOS 開發
- iOS 開發 - 主頁
- iOS 開發 - Xcode IDE
- iOS 開發 - 首次應用程式
- 使應用程式具有互動性
- iOS 開發 - Swift Playground
- 使用 Swift 編寫應用程式
- iOS 開發 - 高階 iOS
- iOS 開發 - 整合地圖
- iOS 開發 - 自動佈局
- iOS 開發 - 動畫
- 訪問 Web 服務
- 併發控制
- 面試問題
- 有用的 iOS 開發資源
- iOS 開發 - 快速指南
- iOS 開發 - 資源
- iOS 開發 - 討論
訪問 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 文件,你可以詳細閱讀有關它的內容。
廣告