在我的应用程序中,我使用 Moya和 Alamofire (还有 Moya/RxSwift 和 Moya-ObjectMapper )用于所有网络请求和响应的库。
我想在一个处理程序中处理所有类型请求的响应,但也可以唯一地处理每个请求。
例如,对于任何请求,我都可以获得“无效版本”的响应,如果出现此错误,我希望避免检查每个响应。
有没有一种优雅的方式来使用 Moya
处理这个用例?
最佳答案
显然这很简单,您只需创建自己的插件即可。并将其添加到您的 Provider 实例中(您可以将其添加到 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)")
}
}
}
关于ios - 如何在一个处理程序中处理所有类型请求的响应,同时使用 Alamofire 和 Moya 唯一地处理每个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706689/