Ios 如何在一个处理程序中处理所有类型请求的响应,同时使用Alamofire和Moya唯一地处理每个请求
在我的应用程序中,我使用and(以及Moya/RxSwift和)库来处理所有网络请求和响应 我希望在一个处理程序中处理所有类型请求的响应,但也要唯一地处理每个请求 例如,对于任何可以得到响应“Not valid Version”的请求,如果出现此错误,我希望避免签入每个响应Ios 如何在一个处理程序中处理所有类型请求的响应,同时使用Alamofire和Moya唯一地处理每个请求,ios,swift,alamofire,moya,Ios,Swift,Alamofire,Moya,在我的应用程序中,我使用and(以及Moya/RxSwift和)库来处理所有网络请求和响应 我希望在一个处理程序中处理所有类型请求的响应,但也要唯一地处理每个请求 例如,对于任何可以得到响应“Not valid Version”的请求,如果出现此错误,我希望避免签入每个响应 使用Moya是否有一种优雅的方法来处理这个用例?显然这很简单,您只需要创建自己的插件。并将其添加到提供者实例中(可以在init函数中添加) 例如: struct NetworkErrorsPlugin: PluginType
使用
Moya
是否有一种优雅的方法来处理这个用例?显然这很简单,您只需要创建自己的插件。并将其添加到提供者实例中(可以在init函数中添加)
例如:
struct NetworkErrorsPlugin: PluginType {
/// Called immediately before a request is sent over the network (or stubbed).
func willSendRequest(request: RequestType, target: TargetType) { }
/// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) {
let responseJSON: AnyObject
if let response = result.value {
do {
responseJSON = try response.mapJSON()
if let response = Mapper<GeneralServerResponse>().map(responseJSON) {
switch response.status {
case .Failure(let cause):
if cause == "Not valid Version" {
print("Version Error")
}
default:
break
}
}
} catch {
print("Falure to prase json response")
}
} else {
print("Network Error = \(result.error)")
}
}
}
struct NetworkErrorsPlugin:PluginType{
///在通过网络(或存根)发送请求之前立即调用。
func willSendRequest(请求:RequestType,目标:TargetType){}
///在收到响应后,但在MoyaProvider调用其完成处理程序之前调用。
func didReceiveResponse(结果:结果,目标:TargetType){
让我们回答约翰逊:任何物体
如果let response=result.value{
做{
responseJSON=try response.mapJSON()
如果let response=Mapper().map(responseJSON){
开关响应状态{
案例。失败(让原因):
如果原因==“版本无效”{
打印(“版本错误”)
}
违约:
打破
}
}
}抓住{
打印(“Falure to prase json响应”)
}
}否则{
打印(“网络错误=\(result.Error)”)
}
}
}
我建议使用通用参数化方法
class DefaultNetworkPerformer {
private var provider: RxMoyaProvider<GitHubApi> = RxMoyaProvider<GitHubApi>()
func performRequest<T:Mappable>(_ request: GitHubApi) -> Observable<T> {
return provider.request(request).mapObject(T.self)
}
}
在这里,您“通知”网络执行者响应将包含User
对象
observable.subscribe {
event in
switch event {
case .next(let user):
//if mapping will succeed here you'll get an Mapped Object. In my case it was User that conforms to Mappable protocol
break
case .error(let error):
//here you'll get MoyaError if something went wrong
break
case .completed:
break
}
}
如何使用以完成闭包作为必需参数的Moya发出请求?
observable.subscribe {
event in
switch event {
case .next(let user):
//if mapping will succeed here you'll get an Mapped Object. In my case it was User that conforms to Mappable protocol
break
case .error(let error):
//here you'll get MoyaError if something went wrong
break
case .completed:
break
}
}