一蛤迎、使用Alamofire進行數(shù)據(jù)請求
1星立,以GET請求為例
(1)不帶參數(shù)聊训,不帶結果處理
Alamofire.request("https://httpbin.org/get")
(2)帶參數(shù),不帶結果處理
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
(3)帶參數(shù),也帶結果處理(這里以返回結果為json格式的為例)
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
.responseJSON { responsein
print(response.request)// original URL request
print(response.response)// URL response
print(response.data)// server data
print(response.result)// result of response serialization
ifletJSON= response.result.value {
print("JSON: \(JSON)")//具體如何解析json內容可看下方“響應處理”部分
}}
2,響應處理(Response Handling)
(1)除了上面樣例使用的responseJSON(處理json類型的返回結果)外,Alamofire還提供了許多其他類型的響應處理方法:
response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
(2)Response Handler
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
.response { responsein
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
ifletdata = response.data,letutf8Text =String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}}
(3)Response Data Handler
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
.responseData { responsein
debugPrint("All Response Info: \(response)")
ifletdata = response.result.value,letutf8Text =String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}}
(4)Response String Handler
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
.responseString { responsein
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
(5)Response JSON Handler
使用responseJSON 方法的話沟启,JSON數(shù)據(jù)會被自動轉化為 Dictionary或Array。假設我們返回的json數(shù)據(jù)格式如下:
[{"name": "hangge","phones": [{"name": "公司","number": "123456"},{"name": "家庭","number":"001"}]},{"name": "big boss","phones": [{"name": "公司","number": "111111"}]}]
使用responseJSON自動解析json數(shù)據(jù):
Alamofire.request("http://www.hangge.com/jsonData.php")
.responseJSON { responsein
switchresponse.result.isSuccess {
case true:
//把得到的JSON數(shù)據(jù)轉為數(shù)組
ifletitems = response.result.valueas?NSArray{
//遍歷數(shù)組得到每一個字典模型
fordictinitems{
print(dict)
}}
case false:
print(response.result.error)
}}
responseJSON也可以配合SwiftyJSON一起使用犹菇,具體可以查看我原來寫的這篇文章:Swift - SwiftyJSON的使用詳解
(6)同樣也支持鏈式的返回結果處理
Alamofire.request("https://httpbin.org/get")
.responseString { responsein
print("Response String: \(response.result.value)")
}.responseJSON { responsein
print("Response JSON: \(response.result.value)")
}
3德迹,請求類型(HTTP Methods)
除了上面使用的.Get類型(不指定的話,默認都是使用Get請求)揭芍。Alamofire還定義了許多其他的HTTP 方法(HTTP Medthods)可以使用胳搞。
publicenumHTTPMethod:String{
caseoptions ="OPTIONS"
caseget="GET"
casehead??? ="HEAD"
casepost??? ="POST"
caseput???? ="PUT"
casepatch?? ="PATCH"
casedelete? ="DELETE"
casetrace?? ="TRACE"
caseconnect ="CONNECT"
}
比如要使用POST請求,把Alamofire.request第二個參數(shù)做修改即可:
Alamofire.request("http://httpbin.org/post", method: .post)
4称杨,請求參數(shù)(Parameters)
(1)使用GET類型請求的時候肌毅,參數(shù)會自動拼接在url后面
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
(2)使用POST類型請求的時候,參數(shù)是放在在HTTP body里傳遞列另,url上看不到
letparameters:[String:Any] = [
"foo":"bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
5芽腾,參數(shù)編碼方式(Parameter Encoding)
除了默認的方式外旦装,Alamofire還支持URL页衙、JSON、PropertyList以及自定義格式方式編碼參數(shù)阴绢。
比如我們想要把一個字典類型的數(shù)據(jù)店乐,使用json格式發(fā)起POST請求:
letparameters:[String:Any] = [
"foo": [1,2,3],
"bar": [
"baz":"qux"
]
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters,
encoding:JSONEncoding.default)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
服務端php頁面可以這么取得發(fā)送過來的JSON數(shù)據(jù):
$postdata= json_decode(file_get_contents("php://input"),TRUE);
$foo=$postdata["foo"];
foreach($fooas$item){
echo$item."|";
}
//輸出:1|2|3|
6,支持自定義Http頭信息(HTTP Headers)
letheaders:HTTPHeaders= [
"Authorization":"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept":"application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers)
.responseJSON { responsein
debugPrint(response)
}
二呻袭、判斷數(shù)據(jù)請求是否成功眨八,并做相應的處理
在請求響應對象之前調用的.validate()函數(shù)是另一個易用的 Alamofire 特性。
將其與請求和響應鏈接左电,以確認響應的狀態(tài)碼在默認可接受的范圍(200到299)內廉侧。如果認證失敗,響應處理方法將出現(xiàn)一個相關錯誤篓足,我們可以根據(jù)不同在完成處理方法中處理這個錯誤段誊。
比如下面的樣例,成功時會打印成功信息栈拖,失敗時輸出具體錯誤信息连舍。
Alamofire.request("https://httpbin.org/get", parameters: ["foo":"bar"])
.validate()
.responseJSON { responsein
switchresponse.result.isSuccess {
casetrue:
print("數(shù)據(jù)獲取成功!")
casefalse:
print(response.result.error)
}}
三、打印調試(print和debugPrint)
不管是request對象還是response對象都是支持打印輸出的涩哟。根據(jù)不同的調試需求索赏,我們可以自行選擇使用print還是debugPrint盼玄。
1,打印request對象
letrequest =Alamofire.request("https://httpbin.org/ip", parameters: ["foo":"bar"])
print(request)
/********** 下面是控制臺輸出 ***************
GEThttps://httpbin.org/ip?foo=bar
******************************************/
letrequest =Alamofire.request("https://httpbin.org/ip", parameters: ["foo":"bar"])
debugPrint(request)
/********** 下面是控制臺輸出 ***************
$ curl -i \
-H "User-Agent: hangge_970/com.hangge.hangge-970 (1; OS Version 9.1 (Build 13B137))" \
-H "Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
-H "Accept-Language: zh-Hans-CN;q=1.0,en-CN;q=0.9" \
******************************************/
2潜腻,打印response對象
Alamofire.request("https://httpbin.org/get")
.responseString { responsein
debugPrint(response)
}
/********** 下面是控制臺輸出 ***************
SUCCESS: {
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding":"gzip;q=1.0,compress;q=0.5",
"Accept-Language":"zh-Hans-CN;q=1.0,en-CN;q=0.9",
"Host":"httpbin.org",
"User-Agent":"hangge_970/com.hangge.hangge-970 (1; OS Version 9.1 (Build 13B137))"
},
"origin":"180.109.163.139",
"url":"https://httpbin.org/get"
}
******************************************/
Alamofire.request(.GET,"https://httpbin.org/get")
.responseString { responsein
print(response)
}
/********** 下面是控制臺輸出 ***************
[Request]: { URL:https://httpbin.org/get}
[Response]: { URL:https://httpbin.org/get} { status code: 200, headers {
"Access-Control-Allow-Origin" = "*";
"Content-Length" = 354;
"Content-Type" = "application/json";
Date = "Tue, 08 Dec 2015 01:57:45 GMT";
Server = nginx;
"access-control-allow-credentials" = true;
} }
[Data]: 354 bytes
[Result]: SUCCESS: {
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding":"gzip;q=1.0,compress;q=0.5",
"Accept-Language":"zh-Hans-CN;q=1.0,en-CN;q=0.9",
"Host":"httpbin.org",
"User-Agent":"hangge_970/com.hangge.hangge-970 (1; OS Version 9.1 (Build 13B137))"
},
"origin":"180.109.163.139",
"url":"https://httpbin.org/get"
}