如何在一个处理程序中处理所有类型请求的响应,同时使用 Alamofire 和 Moya 唯一地处理每个请求

Guy*_*lon 2 ios swift alamofire moya

在我的应用程序中,我使用MoyaAlamofire(以及 Moya/RxSwift 和Moya-ObjectMapper)库来处理所有网络请求和响应。

我想在一个处理程序中处理所有类型请求的响应,但也可以唯一地处理每个请求。

例如,对于任何请求,我都可以获得“无效版本”的响应,如果此错误到达,我想避免检查每个响应。

有没有一种优雅的方法来处理这个用例Moya

Guy*_*lon 5

显然这很简单,您只需创建自己的插件即可。并将其添加到您的 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)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)