有没有办法在 Moya 14 中记录我的请求和响应而不使用 verbose?
container.register(NetworkLoggerPlugin.self) { r in
NetworkLoggerPlugin(verbose: true)
}.inObjectScope(.container)
Run Code Online (Sandbox Code Playgroud)
先感谢您。
其他地方已经给出了为 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
}
}
Run Code Online (Sandbox Code Playgroud)
在您的设置中,添加新插件:
let APIManager = MoyaProvider<API>( plugins: [
VerbosePlugin(verbose: true)
])
Run Code Online (Sandbox Code Playgroud)
这将输出发出的请求和返回的响应。如果响应是 JSON 编码的,它将漂亮地打印 JSON,否则它将尝试打印原始响应数据。
| 归档时间: |
|
| 查看次数: |
3291 次 |
| 最近记录: |