Alamofire.request(.GET, "
print(response.request) // 請求對象
print(response.response) // 響應對象
print(response.data) // 服務端返回的數據
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}</pre>
Alamofire 提供了多種返回數據的序列化方法,比如剛才我們用到的responseJSON, 會返回服務端返回的 JSON 數據,這樣就不用我們自己再去解析了。
下面是 Alamofire 目前支持的數據序列化方法:
- response()
- responseData()
- responseString(encoding: NSStringEncoding)
- responseJSON(options: NSJSONReadingOptions)
- responsePropertyList(options: NSPropertyListReadOptions)
</ol>
支持普通數據,字符串, JSON 和 plist 形式的返回。
上傳文件
Alamofire 提供了 upload 方法用于上傳本地文件到服務器:
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
當然,我們還可以獲取上傳時候的進度:
Alamofire.upload(.POST, "
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
debugPrint(response)
}</pre><br />
還支持 MultipartFormData 形式的表單數據上傳:
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
下載文件
Alamofire 同樣也提供了文件下載的方法:
Alamofire.download(.GET, "
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}</pre>
還可以設置默認的下載存儲位置:
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
也提供了 progress 方法檢測下載的進度:
Alamofire.download(.GET, "
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes read on main queue: \(totalBytesRead)")
}
}
.response { _, _, _, error in
if let error = error {
print("Failed with error: \(error)")
} else {
print("Downloaded file successfully")
}
}</pre><br />
HTTP 驗證
Alamofire 還很提供了一個非常方便的 authenticate 方法提供了 HTTP 驗證:
let user = "user"
let password = "password"
Alamofire.request(.GET, "
HTTP 響應狀態信息識別
Alamofire 還提供了 HTTP 響應狀態的判斷識別,通過 validate 方法,對于在我們期望之外的 HTTP 響應狀態信息,Alamofire 會提供報錯信息:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}
validate 方法還提供自動識別機制,我們調用 validate 方法時不傳入任何參數,則會自動認為 200…299 的狀態嗎為正常: Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print("Validation Successful")
case .Failure(let error):
print(error)
}
}
調試狀態
我們通過使用 debugPrint 函數,可以打印出請求的詳細信息,這樣對我們調試非常的方便:
let request = Alamofire.request(.GET, "
debugPrint(request)</pre>
這樣就會產生如下輸出:
$ curl -i \
-H "User-Agent: Alamofire" \
-H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
-H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
"https://httpbin.org/get?foo=bar"
結語
Alamofire 是一個非常強大并且使用簡潔的網絡操作庫,接口非常的簡單,而且穩定。關于 Alamofire 的更多信息,大家還可以到它的 Github 主頁上面了解到更多。大家也可以下載我們這里個 playground 演示示例: https://github.com/swiftcafex/alamofireSamples
來自:http://www.swiftcafe.io/2015/12/14/alamofire/
本文由用戶
bwnx 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
sesese色