swift 網路請求Alamofire的使用

Hhl發表於2017-12-13

一、使用Alamofire進行資料請求

1,以GET請求為例

(1)不帶引數,不帶結果處理

Alamofire.request("httpbin.org/get")

(2)帶引數,不帶結果處理

Alamofire.request("httpbin.org/get", parameters: ["foo":"bar"])

(3)帶引數,也帶結果處理(這裡以返回結果為json格式的為例)

Alamofire.request("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("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("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("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資料會被自動轉化為 Dictionary或Array。假設我們返回的json資料格式如下:

[{"name": "hangge","phones": [{"name": "公司","number": "123456"},{"name": "家庭","number":"001"}]},{"name": "big boss","phones": [{"name": "公司","number": "111111"}]}]

使用responseJSON自動解析json資料:

Alamofire.request("www.hangge.com/jsonData.ph…")

.responseJSON { responsein

switchresponse.result.isSuccess {

case true:

//把得到的JSON資料轉為陣列

ifletitems = response.result.valueas?NSArray{

//遍歷陣列得到每一個字典模型

fordictinitems{

print(dict)

}}

case false:

print(response.result.error)

}}

responseJSON也可以配合SwiftyJSON一起使用,具體可以檢視我原來寫的這篇文章:Swift - SwiftyJSON的使用詳解

(6)同樣也支援鏈式的返回結果處理

Alamofire.request("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第二個引數做修改即可:

Alamofire.request("httpbin.org/post", method: .post)

4,請求引數(Parameters)

(1)使用GET型別請求的時候,引數會自動拼接在url後面

Alamofire.request("httpbin.org/get", parameters: ["foo":"bar"])

//httpbin.org/get?foo=bar

(2)使用POST型別請求的時候,引數是放在在HTTP body裡傳遞,url上看不到

letparameters:[String:Any] = [

"foo":"bar",

"baz": ["a", 1],

"qux": [

"x": 1,

"y": 2,

"z": 3

]

]

Alamofire.request("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,引數編碼方式(Parameter Encoding)

除了預設的方式外,Alamofire還支援URL、JSON、PropertyList以及自定義格式方式編碼引數。

比如我們想要把一個字典型別的資料,使用json格式發起POST請求:

letparameters:[String:Any] = [

"foo": [1,2,3],

"bar": [

"baz":"qux"

]

]

Alamofire.request("httpbin.org/post", method: .post, parameters: parameters,

encoding:JSONEncoding.default)

// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}

服務端php頁面可以這麼取得傳送過來的JSON資料:

$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("httpbin.org/headers", headers: headers)

.responseJSON { responsein

debugPrint(response)

}

二、判斷資料請求是否成功,並做相應的處理

在請求響應物件之前呼叫的.validate()函式是另一個易用的 Alamofire 特性。

將其與請求和響應連結,以確認響應的狀態碼在預設可接受的範圍(200到299)內。如果認證失敗,響應處理方法將出現一個相關錯誤,我們可以根據不同在完成處理方法中處理這個錯誤。

比如下面的樣例,成功時會列印成功資訊,失敗時輸出具體錯誤資訊。

Alamofire.request("httpbin.org/get", parameters: ["foo":"bar"])

.validate()

.responseJSON { responsein

switchresponse.result.isSuccess {

casetrue:

print("資料獲取成功!")

casefalse:

print(response.result.error)

}}

三、列印除錯(print和debugPrint)

不管是request物件還是response物件都是支援列印輸出的。根據不同的除錯需求,我們可以自行選擇使用print還是debugPrint。

1,列印request物件

letrequest =Alamofire.request("httpbin.org/ip", parameters: ["foo":"bar"])

print(request)

/********** 下面是控制檯輸出 ***************

GEThttpbin.org/ip?foo=bar

******************************************/

letrequest =Alamofire.request("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" \

"httpbin.org/ip?foo=bar"

******************************************/

2,列印response物件

Alamofire.request("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":"httpbin.org/get"

}

******************************************/

Alamofire.request(.GET,"httpbin.org/get")

.responseString { responsein

print(response)

}

/********** 下面是控制檯輸出 ***************

[Request]: { URL:httpbin.org/get}

[Response]: { URL: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":"httpbin.org/get"

}

原文連結:swift 資料請求Alamofire的使用

相關文章