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

标签 ios swift alamofire moya

在我的应用程序中,我使用 MoyaAlamofire (还有 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/

相关文章:

ios - 调整容器中页面 View 的大小

ios - 如何在 UIAlertAction 中传递多个处理程序

swift - 如何添加 Alamofire URL 参数

swift - 声明枚举路由器 Alamofire swift 2.0

ios - AdMob 横幅 View 背景颜色为黑色,需要白色或透明

ios - 如何在 iOS 10 上从 Xcode 安装应用程序?

ios - Firebase 快照中未显示的数据是否安全?

iOS : Why do we need to add child view controller when adding view as subview does the work?

swift - 映射结构数组

ios - 在 ios 中发送 json 对象数组