IOS高级工程师贾正亮
好久没有更新简书了Swift Moya 的使用
import Moya
importHandyJSON
importMBProgressHUD
letLoadingPlugin =NetworkActivityPlugin{ (type, target)in
guard let vc = topVC else { return }
switchtype {
case.began:
MBProgressHUD.hide(for: vc.view, animated:false)
MBProgressHUD.showAdded(to: vc.view, animated:true)
case.ended:
MBProgressHUD.hide(for: vc.view, animated:true)
}
}
lettimeoutClosure = {(endpoint:Endpoint, closure:MoyaProvider.RequestResultClosure) ->Voidin
ifvarurlRequest =try? endpoint.urlRequest() {
urlRequest.timeoutInterval=20
closure(.success(urlRequest))
}else{
closure(.failure(MoyaError.requestMapping(endpoint.url)))
}
}
letApiProvider =MoyaProvider(requestClosure:timeoutClosure)
letApiLoadingProvider =MoyaProvider(requestClosure:timeoutClosure, plugins: [LoadingPlugin])
请求分类
enum UApi {
casesearchHot//搜索热门
casesearchRelative(inputText:String)//相关搜索
casesearchResult(argCon:Int, q:String)//搜索结果
caseboutiqueList(sexType:Int)//推荐列表
casespecial(argCon:Int, page:Int)//专题
casevipList//VIP列表
casesubscribeList//订阅列表
caserankList//排行列表
casecateList//分类列表
casecomicList(argCon:Int, argName:String, argValue:Int, page:Int)//漫画列表
caseguessLike//猜你喜欢
casedetailStatic(comicid:Int)//详情(基本)
casedetailRealtime(comicid:Int)//详情(实时)
casecommentList(object_id:Int, thread_id:Int, page:Int)//评论
casechapter(chapter_id:Int)//章节内容
}
//请求配置 实现TargetType协议
extension UApi: TargetType {
//服务器地址
var baseURL: URL { return URL(string: "http://app.u17.com/v3/appV3_3/ios/phone")! }
//各个请求的具体路径
varpath:String{
switchself{
case .searchHot: return "search/hotkeywordsnew"
case .searchRelative: return "search/relative"
case .searchResult: return "search/searchResult"
case .boutiqueList: return "comic/boutiqueListNew"
case .special: return "comic/special"
case .vipList: return "list/vipList"
case .subscribeList: return "list/newSubscribeList"
case.rankList:return"rank/list"
case .cateList: return "sort/mobileCateList"
case .comicList: return "list/commonComicList"
case .guessLike: return "comic/guessLike"
case .detailStatic: return "comic/detail_static_new"
case .detailRealtime: return "comic/detail_realtime"
case .commentList: return "comment/list"
case .chapter: return "comic/chapterNew"
}
}
//请求类型
varmethod:Moya.Method{return.get}
//请求任务事件(这里附带上参数)
vartask:Task{
var parmeters: [String:Any] = [:]
switch self{
case.searchRelative(letinputText):
parmeters["inputText"] = inputText
case.searchResult(letargCon,letq):
parmeters["argCon"] = argCon
parmeters["q"] = q
case.boutiqueList(letsexType):
parmeters["sexType"] = sexType
case.special(letargCon,letpage):
parmeters["argCon"] = argCon
parmeters["page"] =max(1, page)
case.comicList(letargCon,letargName,letargValue,letpage):
parmeters["argCon"] = argCon
ifargName.count>0{ parmeters["argName"] = argName }
parmeters["argValue"] = argValue
parmeters["page"] =max(1, page)
case.detailStatic(letcomicid),
.detailRealtime(letcomicid):
parmeters["comicid"] = comicid
case.commentList(letobject_id,letthread_id,letpage):
parmeters["object_id"] = object_id
parmeters["thread_id"] = thread_id
parmeters["page"] = page
case.chapter(letchapter_id):
parmeters["chapter_id"] = chapter_id
default: break
}
return.requestParameters(parameters: parmeters, encoding:URLEncoding.default)
}
//这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
varsampleData:Data{return"".data(using:String.Encoding.utf8)! }
//请求头
varheaders: [String:String]? {returnnil}
}
extension Response {
funcmapModel(_type:T.Type)throws->T{
letjsonString =String(data:data, encoding: .utf8)
guardletmodel =JSONDeserializer.deserializeFrom(json: jsonString)else{
throw MoyaError.jsonMapping(self)
}
returnmodel
}
}
MoyaProvider类的扩展
extension MoyaProvider {
@discardableResult
openfuncrequest(_target:Target,
model:T.Type,
completion: ((_returnData:T?) ->Void)?) ->Cancellable? {
returnrequest(target, completion: { (result)in
guardletcompletion = completionelse{return}
guardletreturnData =try? result.value?.mapModel(ResponseData.self)else{
completion(nil)
return
}
completion(returnData.data?.returnData)
})
}
}