如何在一个处理程序中处理所有类型的请求的响应,又如何使用Alamofire和Moya唯一地处理每个请求 [英] How to handle the response of all types of requests in one handler, but also uniquely handle every request with Alamofire and Moya
问题描述
在我的应用中,我使用 Moya 和 Alamofire (还有Moya / RxSwift和 Moya-ObjectMapper )用于所有网络请求和响应的库。
In my app I use Moya and Alamofire (And also Moya/RxSwift and Moya-ObjectMapper) libraries for all network requests and responses.
我想在一个处理程序中处理所有类型的请求的响应,但还要唯一地处理每个请求。
I would like to handle the response of all types of requests in one handler, but also uniquely handle every request.
例如,对于任何请求,我都可以获取响应无效版本,如果出现此错误,我想避免检查每个响应。
For example for any request I can get the response "Not valid Version", I would like to avoid to check in every response if this error arrived.
是否有一种优雅的方式来使用 Moya
处理此用例?
Is there an elegant way to handle this use case with Moya
?
推荐答案
显然,这很简单,您只需要创建自己的插件即可。并将其添加到您的Provider实例中(您可以在init函数中添加它)
Apparently that is very simple, You just should create your own plugin. And add it to your Provider instance (You can add it in the init function)
例如:
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)")
}
}
}
这篇关于如何在一个处理程序中处理所有类型的请求的响应,又如何使用Alamofire和Moya唯一地处理每个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!