Swift在做请求的时候大家可能都是封装成一个单利,进行调用,今天在这里我这边把自己封装的请求和上传图片代码给大家写成一篇文章,我这边用到的第三方库有AFN3.0, ObjectMapper(json转model)8.0也可以使用.接下来直接就先上代码:
//网络请求单利
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!
}
}
这个单利里面有一个Cookie大家可以去掉的,因为这个是我们这边自己和后台定义的一个值,相当于大家的Token,因为不是很清晰,所以我这边也把截图给大家进行一个展示,下面是图片:
到这里我们就该封装post请求了,我们这里使用了一个基类的Model,和定义了两个Block,这样的原因是我们为了之后在请求来数据的时候方便,并且可以在转model也会简便很多,这里大家可以更改的,接下来就是代码:
//请求服务器
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请求的一个封装,图片是:
接下来我们说下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)
}
}
这里我们可以看出,我们进行了拆分接下来是拆分的代码:
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])
}
}
}
我们先大概说下这个方法,这里是我们后台根据图片名字不同进行接收,并且项目中定义了好几个名字,所以之前我们这样写的,但是我们之后改过了,具体怎么改大家可以思考下,当然写在这里也可以,只是看着比较笨的,😄,接下来我们发最后一个方法:
@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
}
好了,到这里我们上传图片的方法就也封装好了,接下来我们上图:
本想给大家详细讲解的,但是我目前还是在上班,所以就不写那么多了,任务来了,之后不理解或者其他问题可以加我QQ:1030554941,我这边随时在线,看到后会给大家进行回复的,希望大家看过后可以给一个赞,谢谢,如果需要源码的可以加我QQ要,因为我这边不喜欢github上传东西,望大家理解,谢谢