Version of Moya is 8.04
I have read the Endpoints document which makes me know how to set httpHearderFields,like this:
let endpointClosure = { (target: MyTarget) -> Endpoint<MyTarget> in
let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
return defaultEndpoint.adding(newHTTPHeaderFields: ["APP_NAME": "MY_AWESOME_APP"])
}
let provider = MoyaProvider<GitHub>(endpointClosure: endpointClosure)
but,I also get another problem? When we create a provider, we need to pass the endpointClosure to it. For me,the provider is a property in the ViewController, I use a function to create the provider.
var provider:RxMoyaProvider<HTTPService>!
func setupProvider() {
let endpointClosure = { (target: HTTPService) -> Endpoint<HTTPService> in
let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
return defaultEndpoint.adding(newHTTPHeaderFields: ["Accept":"application/json"])
}
provider = RxMoyaProvider<HTTPService>(endpointClosure: endpointClosure)
}
Now,I need to set httpHearderFields for every request, I don't want to write the same code to create endpointClosure in every ViewController. How can I add httpHeaderFields in automatic for every request?
Hi @longshihua,
you have a few options here. The way I usually do is to create a static function on property that returns a provider to me. I usually do this in a separate struct or class in way that I can have a separate implementation for tests if necessary.
Something like this:
struct HTTPServiceProvider {
static var shared: RxMoyaProvider<HTTPService> = {
let endpointClosure = { (target: HTTPService) -> Endpoint<HTTPService> in
let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
return defaultEndpoint.adding(newHTTPHeaderFields: ["Accept":"application/json"])
}
provider = RxMoyaProvider<HTTPService>(endpointClosure: endpointClosure)
}()
}
But I suppose you can also use your setupProvider making it static in the struct above and call it from your view controller.
A third option would be to have the setupProvider as a function in an extension of UIViewController, but I would not recommend this one as it's the least clear IMHO.
On a side note, dealing with header fields will (hopefully) be easier in 9.0.0 (see #1067) :wink:
@alcarvalho and @pedrovereza ,thanks guys.
I'm gonna close this issue for now, but if you'll have more questions about this topic, please feel free to reopen it whenever 馃憤
Most helpful comment
On a side note, dealing with header fields will (hopefully) be easier in
9.0.0(see #1067) :wink: