關(guān)于 Alamofire
如果你曾經(jīng)用 Objective-C 開發(fā)過 iOS 應(yīng)用程序滑黔,那么你一定不會對 AFNetworking 這個(gè)第三方庫感到陌生总寻。AFNetworking 作為常用的網(wǎng)絡(luò)請求庫辫红,以其簡潔和優(yōu)雅的特性系吭,廣受 iOS 應(yīng)用開發(fā)者贊譽(yù)啡直。自從 Swift 編程語言在一夜之間占領(lǐng)全世界之后箫柳,AFNetworking 的作者 Mattt Thompson 又馬不停蹄地發(fā)起了一個(gè)基于 Swift 的網(wǎng)絡(luò)請求庫讼育,這便是 Alamofire帐姻。Alamofire 并非是 AFNetworking 的 Swift 翻版,而是一個(gè)全新的項(xiàng)目奶段。這個(gè)庫秉承了作者一貫的高質(zhì)量饥瓷,截至今天,其在 Github 上面已經(jīng)收獲了接近 18000 個(gè) star痹籍。Alamofire 的代碼干凈呢铆、清晰,而且總量還不到 1000 行蹲缠,非常適合作為示例進(jìn)行學(xué)習(xí)刺洒。通過對該庫的學(xué)習(xí),我們將:1. 了解 Swift 的常用編程范式以及編程技巧吼砂;2. 了解 Apple 的 URL Loading System逆航。
本文介紹了一些簡單的用法示例,借此管窺 Alamofire 的特性渔肩。
一個(gè) GET 請求
Alamofire 的接口使用起來非常簡單因俐,比如,你可以這樣發(fā)送一個(gè) GET 請求:
Alamofire.request(.GET, "http://httpbin.org/get")
.response { (request, response, data, error) in
print(data)
}
解析返回值
默認(rèn)情況下,你會在 response
閉包中得到一個(gè) NSData
對象抹剩。如果你希望得到字符串對象撑帖,可以使用 responseString
:
Alamofire.request(.GET, "http://httpbin.org/get")
.responseString { (request, response, string, error) in
print(string)
}
同樣,你也可以得到 JSON
對象:
Alamofire.request(.GET, "http://httpbin.org/get")
.responseJSON {(request, response, JSON, error) in
print(JSON)
}
進(jìn)度監(jiān)聽
你可以提供一個(gè) progress
閉包澳眷,用以監(jiān)聽請求的進(jìn)度:
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// 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
print(response)
}
鏈?zhǔn)秸{(diào)用
得益于 Swift 提供的語法支持胡嘿,Alamofire 提供的鏈?zhǔn)秸{(diào)用機(jī)制令網(wǎng)絡(luò)請求十分簡潔與直觀:
Alamofire.request(.GET, "http://httpbin.org/get")
.authenticate(HTTPBasic: user, password: password)
.progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
print(totalBytesRead)
}
.validate()
.responseJSON { (request, response, JSON, error) in
print(JSON)
}
.responseString { (request, response, string, error) in
print(string)
}
將請求轉(zhuǎn)為等效的 cURL 命令
有時(shí)候你可能需要使用 curl 命令對網(wǎng)絡(luò)請求進(jìn)行調(diào)試。Alamofire 幫你把請求轉(zhuǎn)換為等效的 curl 命令:
let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
debugPrint(request)
這將得到如下輸出:
$ 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"
參考
(未完)