前言
Alamofire是一個(gè)使用Swift開發(fā)的網(wǎng)絡(luò)請(qǐng)求庫(kù),其開發(fā)團(tuán)隊(duì)是AFNetworking的原團(tuán)隊(duì)。它語(yǔ)法簡(jiǎn)潔,采用鏈?zhǔn)骄幊痰乃枷耄褂闷饋?lái)是相當(dāng)?shù)氖娣1举|(zhì)是基于NSURLSession進(jìn)行封裝。接下開我們就進(jìn)入實(shí)戰(zhàn),開始學(xué)習(xí)Alamofire的使用。
GET請(qǐng)求
常用的get請(qǐng)求示例以及請(qǐng)求結(jié)果
Alamofire.request("https://httpbin.org/get", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if(response.error == nil){
LLog("請(qǐng)求成功")
LLog(response.result.value)
}else{
LLog("請(qǐng)求失敗\(String(describing: response.error))")
}
}
Get請(qǐng)求、有參數(shù)、使用Basic Auth授權(quán)訪問(wèn)(例如:jira)
var header:HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: "xxxx", password: "xxxxxx") {
header[authorizationHeader.key] = authorizationHeader.value
}
// 此處的 URLEncoding.default (URLEncoding.queryString )會(huì)將parameters 拼接到url后面
Alamofire.request("https://httpbin.org/get", method: HTTPMethod.get, parameters: ["key":"value"], encoding: URLEncoding.default, headers: header).responseJSON { (response) in
if(response.error == nil){
LLog("請(qǐng)求成功")
LLog(response.result.value)
}else{
LLog("請(qǐng)求失敗\(String(describing: response.error))")
}
}
POST請(qǐng)求 常用的post請(qǐng)求
Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["key1":"value1","key2":"value2"], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if(response.error == nil){
LLog("請(qǐng)求成功")
LLog(response.result.value)
}else{
LLog("請(qǐng)求失敗\(String(describing: response.error))")
}
}
post請(qǐng)求,提交json格式的數(shù)據(jù)
// JSONEncoding.default === JSONEncoding.prettyPrinted
Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["key1":"value1","key2":"value2"], encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
if(response.error == nil){
LLog("請(qǐng)求成功")
LLog(response.result.value)
}else{
LLog("請(qǐng)求失敗\(String(describing: response.error))")
}
}
PUT、Delete 請(qǐng)求 參照POST(使用區(qū)別不大)
UPLOAD(上傳文件)
上傳文件示例
let data:Data = UIImageJPEGRepresentation(#imageLiteral(resourceName: "beauty.jpeg"), 0.2)!
let url = Bundle.main.url(forResource: "beauty", withExtension: "jpeg");
// 多文件上傳
Alamofire.upload(multipartFormData: { (formdata) in
formdata.append(data, withName: "file", fileName: "beauty.jpeg", mimeType: "image/jpeg")
formdata.append(url!, withName: "file2")
}, to: UPLOAD_URL) { (encodingResult) in
switch encodingResult{
case .success(let uploadFile, _, _):
//上傳進(jìn)度回調(diào)
uploadFile.uploadProgress(closure: { (progress) in
debugPrint("上傳進(jìn)度\(progress)")
})
//上傳結(jié)果回調(diào)
uploadFile.responseString(completionHandler: { (response) in
LLog(response.result.value)
})
break
case .failure( let error):
LLog(error);
break
}
}
備注:
想必大家也注意到上面的上傳圖片的代碼,在append data的時(shí)候多了一個(gè) filename的參數(shù),在測(cè)試的時(shí)候,我發(fā)現(xiàn)這個(gè)參數(shù)是必須的,如果你傳入的是data數(shù)據(jù),但是如果你使用的是fileurl則可以不用這個(gè)參數(shù),在alamofire中 會(huì)自己獲取文件的名。
如果我們?cè)赼ppend data的時(shí)候,不傳入文件名,在上面的代碼中 headers中則不會(huì)有 filename這個(gè)參數(shù),此時(shí)使用charles抓包是會(huì)發(fā)現(xiàn)如下。
上傳文件并攜帶參數(shù)
var param: [String:String] = [:];
param["postion"] = "portrait"
let url = Bundle.main.url(forResource: "beauty", withExtension: "jpeg");
// 2、多文件上傳
Alamofire.upload(multipartFormData: { (formdata) in
formdata.append(url!, withName: "file2")
//拼接參數(shù)
for (key, value) in param {
formdata.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: UPLOAD_URL) { (encodingResult) in
switch encodingResult{
case .success(let uploadFile, _, _):
//上傳進(jìn)度回調(diào)
uploadFile.uploadProgress(closure: { (progress) in
debugPrint("上傳進(jìn)度\(progress)")
})
//上傳結(jié)果回調(diào)
uploadFile.responseJSON(completionHandler: { (response) in
LLog(response.result.value)
})
break
case .failure( let error):
LLog(error);
break
}
}
備注:在我們的實(shí)際開發(fā)中,后臺(tái)有時(shí)候并沒(méi)有配置專門的文件服務(wù)器,這個(gè)時(shí)候我們往往就需要在上傳文件的時(shí)候,配置必要的參數(shù),來(lái)表明我們上傳文件資源的目的。
最后
Alamofire真的是一個(gè)很好用的網(wǎng)絡(luò)請(qǐng)求庫(kù),同學(xué)們,趕緊開始使用吧!