【问题标题】:Logging response and request in Moya 14在 Moya 14 中记录响应和请求
【发布时间】:2020-04-28 11:56:50
【问题描述】:

有什么方法可以在不使用详细信息的情况下在 Moya 14 中记录我的请求和响应?

container.register(NetworkLoggerPlugin.self) { r in
   NetworkLoggerPlugin(verbose: true)
   }.inObjectScope(.container)

提前谢谢你。

【问题讨论】:

    标签: swift moya


    【解决方案1】:

    最初的指导是 elsewhere 为 Moya 创建一个自定义插件,但这里有一个详细插件的工作示例,它将显示请求和响应数据。

    将以下代码添加到您调用 Moya 的任何位置:

    struct VerbosePlugin: PluginType {
        let verbose: Bool
    
        func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
            #if DEBUG
            if let body = request.httpBody,
               let str = String(data: body, encoding: .utf8) {
                if verbose {
                    print("request to send: \(str))")
                }
            }
            #endif
            return request
        }
    
        func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
            #if DEBUG
            switch result {
            case .success(let body):
                if verbose {
                    print("Response:")
                    if let json = try? JSONSerialization.jsonObject(with: body.data, options: .mutableContainers) {
                        print(json)
                    } else {
                        let response = String(data: body.data, encoding: .utf8)!
                        print(response)
                    }
                }
            case .failure( _):
                break
            }
            #endif
        }
    
    }
    

    在您的设置中,添加新插件:

    let APIManager = MoyaProvider<API>( plugins: [
        VerbosePlugin(verbose: true)
        ])
    

    这将输出正在发出的请求和返回的响应。如果响应是 JSON 编码的,它将漂亮地打印 JSON,否则它将尝试打印出原始响应数据。

    【讨论】:

      【解决方案2】:

      MoyaProvider(插件:[NetworkLoggerPlugin()])

      【讨论】:

      • 这是一个用于打印活动的内置类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 2019-01-10
      • 2023-04-02
      • 2018-04-19
      相关资源
      最近更新 更多