问题
How do we debug the request being set over to backend servers?
I'd like to be able to see exactly or print out the full request with headers parameters, etc... that is being sent over to servers whenever I make any request by Moya
回答1:
It is done by activating a plugin that Moya
Already has it. it is NetworkLoggerPlugin
. I need to change this line of code:
var provider = MoyaProvider<MainAPI>()
with:
var provider = MoyaProvider<MainAPI>(plugins: [NetworkLoggerPlugin(verbose: true)])
Thanks to @Anbu.Karthik
回答2:
If using Moya from 14, you can make your own verbose Plugin, like this:
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) {
print("request to send: \(str))")
}
#endif
return request
}
}
and use: let provider = MoyaProvider<AuthService>(plugins: [VerbosePlugin(verbose: true)])
回答3:
- use this to setup the provider
let provider: MoyaProvider<API> = MoyaProvider<API>(plugins: [NetworkLoggerPlugin()]
- in
NetworkLoggerPlugin.swift
file of Moya pod you can changelogOptions
inside theConfiguration
struct given. In the init methodlogOptions: LogOptions = .requestBody
can be changed. It's an enum. So you can try changing the logOptions value as you wish.
* I think it's okay to change a pod file because it doesn't affect the code base since this is a developer side logging option
回答4:
Cross-posted:
Here's a working example of a verbose plugin that will display both request and response data.
Add the following code to wherever you are calling Moya from:
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
}
}
In your set up, add the new plugin:
let APIManager = MoyaProvider<API>( plugins: [
VerbosePlugin(verbose: true)
])
This will output both the request being made and the response returned. If the response is JSON encoded, it will pretty-print the JSON, otherwise it will attempt to print out the raw response data.
来源:https://stackoverflow.com/questions/54105560/how-do-we-debug-see-the-request-being-set-over-api-with-moya