swift 網(wǎng)絡(luò)請求Alamofire的使用

一、使用Alamofire進(jìn)行數(shù)據(jù)請求

1,以GET請求為例

(1)不帶參數(shù),不帶結(jié)果處理

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

(2)帶參數(shù),不帶結(jié)果處理

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

(3)帶參數(shù),也帶結(jié)果處理(這里以返回結(jié)果為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內(nèi)容可看下方“響應(yīng)處理”部分

}}

2,響應(yīng)處理(Response Handling)

(1)除了上面樣例使用的responseJSON(處理json類型的返回結(jié)果)外,Alamofire還提供了許多其他類型的響應(yīng)處理方法:

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ù)會(huì)被自動(dòng)轉(zhuǎn)化為 Dictionary或Array。假設(shè)我們返回的json數(shù)據(jù)格式如下:

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

使用responseJSON自動(dòng)解析json數(shù)據(jù):

Alamofire.request("http://www.hangge.com/jsonData.php")

.responseJSON { responsein

switchresponse.result.isSuccess {

case true:

//把得到的JSON數(shù)據(jù)轉(zhuǎn)為數(shù)組

ifletitems = response.result.valueas?NSArray{

//遍歷數(shù)組得到每一個(gè)字典模型

fordictinitems{

print(dict)

}}

case false:

print(response.result.error)

}}

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

(6)同樣也支持鏈?zhǔn)降姆祷亟Y(jié)果處理

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類型(不指定的話,默認(rèn)都是使用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第二個(gè)參數(shù)做修改即可:

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

4,請求參數(shù)(Parameters)

(1)使用GET類型請求的時(shí)候,參數(shù)會(huì)自動(dòng)拼接在url后面

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

//https://httpbin.org/get?foo=bar

(2)使用POST類型請求的時(shí)候,參數(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)

除了默認(rèn)的方式外,Alamofire還支持URL、JSON、PropertyList以及自定義格式方式編碼參數(shù)。

比如我們想要把一個(gè)字典類型的數(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"}}

服務(wù)端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ù)請求是否成功,并做相應(yīng)的處理

在請求響應(yīng)對象之前調(diào)用的.validate()函數(shù)是另一個(gè)易用的 Alamofire 特性。

將其與請求和響應(yīng)鏈接,以確認(rèn)響應(yīng)的狀態(tài)碼在默認(rèn)可接受的范圍(200到299)內(nèi)。如果認(rèn)證失敗,響應(yīng)處理方法將出現(xiàn)一個(gè)相關(guān)錯(cuò)誤,我們可以根據(jù)不同在完成處理方法中處理這個(gè)錯(cuò)誤。

比如下面的樣例,成功時(shí)會(huì)打印成功信息,失敗時(shí)輸出具體錯(cuò)誤信息。

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

.validate()

.responseJSON { responsein

switchresponse.result.isSuccess {

casetrue:

print("數(shù)據(jù)獲取成功!")

casefalse:

print(response.result.error)

}}

三、打印調(diào)試(print和debugPrint)

不管是request對象還是response對象都是支持打印輸出的。根據(jù)不同的調(diào)試需求,我們可以自行選擇使用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" \

"https://httpbin.org/ip?foo=bar"

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

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"

}

原文鏈接:swift 數(shù)據(jù)請求Alamofire的使用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容