Swift在做請(qǐng)求的時(shí)候大家可能都是封裝成一個(gè)單利宾袜,進(jìn)行調(diào)用,今天在這里我這邊把自己封裝的請(qǐng)求和上傳圖片代碼給大家寫成一篇文章驾窟,我這邊用到的第三方庫(kù)有AFN3.0, ObjectMapper(json轉(zhuǎn)model)8.0也可以使用.接下來(lái)直接就先上代碼:
//網(wǎng)絡(luò)請(qǐng)求單利
classManagerRequest:AFHTTPSessionManager{
staticletshareInstance =ManagerRequest()
privatevarselfManager:AFHTTPSessionManager?
funcApiManager() ->AFHTTPSessionManager{
if selfManager ==nil{
selfManager = AFHTTPSessionManager()
selfManager?.requestSerializer.timeoutInterval =30
selfManager?.responseSerializer.acceptableContentTypes = ["text/html"]
ifcookie!=nil{
selfManager?.requestSerializer.setValue("spxux=\(cookie!)", forHTTPHeaderField:"Cookie")
}
selfManager?.responseSerializer = AFHTTPResponseSerializer()
}
returnselfManager!
}
}
這個(gè)單利里面有一個(gè)Cookie大家可以去掉的庆猫,因?yàn)檫@個(gè)是我們這邊自己和后臺(tái)定義的一個(gè)值,相當(dāng)于大家的Token绅络,因?yàn)椴皇呛芮逦暮罚晕疫@邊也把截圖給大家進(jìn)行一個(gè)展示,下面是圖片:
到這里我們就該封裝post請(qǐng)求了昨稼,我們這里使用了一個(gè)基類的Model节视,和定義了兩個(gè)Block,這樣的原因是我們?yōu)榱酥笤谡?qǐng)求來(lái)數(shù)據(jù)的時(shí)候方便假栓,并且可以在轉(zhuǎn)model也會(huì)簡(jiǎn)便很多寻行,這里大家可以更改的匾荆,接下來(lái)就是代碼:
//請(qǐng)求服務(wù)器
funcRequstmanager(method:String,_paramas: [String:Any]?,_failuer:@escapingfailerBlock
,_success:@escapingsuccessBlock) {
ManagerRequest.shareInstance.ApiManager().post("\(HOST)\(method)", parameters: paramas, progress: { (gress)in
}, success: { (session, respData)in
ifrespData !=nil{
letrespStr = String(data: respDataas! Data, encoding: .utf8)
ifrespStr !=nil{
letmodel = BaseModel(JSONString: respStr!)
success(model)
}else{
DispatchQueue.main.async {
failuer(session.error)
}
}
}
}) { (session, error)in
DispatchQueue.main.async {
failuer(error)
}
}
}
到這里是我們post請(qǐng)求的一個(gè)封裝拌蜘,圖片是:
接下來(lái)我們說(shuō)下post上傳圖片的代碼和大概做法:
funcRequstImage(type:Int,_method:String,_imageArray:[AnyObject],_params:[String:AnyObject]?,_failer:@escapingfailerBlock,_success:@escapingsuccessBlock){
ManagerRequest.shareInstance.ApiManager().post("\(HOST)\(method)", parameters: params, constructingBodyWith: { (_formData: AFMultipartFormData)in
print("imageArray,\(imageArray)")
imageForecth(type:type,formData: formData, params: imageArray)
dataTypeCheck(formData: formData, params: params)
}, progress:nil, success: { (session, respData)in
ifrespData !=nil{
letrespStr = String(data: respDataas! Data, encoding: .utf8)
print(respStr)
ifrespStr !=nil{
letmodel = BaseModel(JSONString: respStr!)
success(model)
}else{
failer(session.error)
}
}
}) { (fauile, err)in
print(err)
}
}
這里我們可以看出,我們進(jìn)行了拆分接下來(lái)是拆分的代碼:
funcimageForecth(type:Int,formData:AFMultipartFormData, params: [AnyObject]?){
vardataimage =NSData()
varj =0
varname =""
foriinparams!{
switchtype {
case1:
name ="cust_img"
break
case2:
name ="diary_pics\(j)"
break
case3:
name ="didi_pics\(j)"
break
default:
break
}
ifiisDictionary{
letimg_dic = ias!Dictionary
for(key,value)inimg_dic{
letdic_img = value
ifUIImagePNGRepresentation(dic_img) !=nil{
dataimage =UIImageJPEGRepresentation(value,0.2)!asNSData
}else{
dataimage =UIImagePNGRepresentation(value)!asNSData
}
formData.appendPart(withFileData: dataimageasData, name: key, fileName:"xxxx.png", mimeType:"image/jpeg")
}
}elseifiisUIImage{
letimg = ias!UIImage
ifUIImagePNGRepresentation(img) !=nil{
ifUIImagePNGRepresentation(img) !=nil{
dataimage =UIImageJPEGRepresentation(img,0.2)!asNSData
}else{
dataimage =UIImagePNGRepresentation(img)!asNSData
}
}else{
formData.appendPart(withFileData: dataimageasData, name: name, fileName:"xxxx.png", mimeType:"image/jpeg")
dataimage =UIImagePNGRepresentation(img)!asNSData
}
formData.appendPart(withFileData: dataimageasData, name: name, fileName:"xxxx.png", mimeType:"image/jpeg")
j +=1
}elseifiis[UIImage] {
imageForecth(type: type,formData: formData, params: ias? [AnyObject])
}
}
}
我們先大概說(shuō)下這個(gè)方法牙丽,這里是我們后臺(tái)根據(jù)圖片名字不同進(jìn)行接收简卧,并且項(xiàng)目中定義了好幾個(gè)名字,所以之前我們這樣寫的烤芦,但是我們之后改過(guò)了举娩,具體怎么改大家可以思考下,當(dāng)然寫在這里也可以构罗,只是看著比較笨的铜涉,??辛馆,接下來(lái)我們發(fā)最后一個(gè)方法:
@discardableResultfuncdataTypeCheck(formData:AFMultipartFormData, params: [String:AnyObject]?) ->AFMultipartFormData? {
for(key, value)inparams! {
switchvalue {
caseisBool, isInt, isString, isFloat,isDouble,isCGFloat,isData:
formData.appendPart(withForm:"\(value)".data(using: String.Encoding.utf8)!, name: key)
caseisDictionary:
dataTypeCheck(formData: formData, params: params)
default:
break
}
}
returnformData
}
好了嘹裂,到這里我們上傳圖片的方法就也封裝好了,接下來(lái)我們上圖:
本想給大家詳細(xì)講解的茉继,但是我目前還是在上班盖彭,所以就不寫那么多了纹烹,任務(wù)來(lái)了,之后不理解或者其他問(wèn)題可以加我QQ:1030554941召边,我這邊隨時(shí)在線铺呵,看到后會(huì)給大家進(jìn)行回復(fù)的,希望大家看過(guò)后可以給一個(gè)贊掌实,謝謝陪蜻,如果需要源碼的可以加我QQ要,因?yàn)槲疫@邊不喜歡github上傳東西贱鼻,望大家理解宴卖,謝謝