I was migrating my code to Swift 3 and updated Alamofire to the swift 3 branch.
There, the suggested way of handling parameter encoding is to use one of the new ParameterEncoding
conforming structs, such as URLEncoding
, that has an encode
method.
The problem is that this method now throws, which makes sense, but the URLRequestConvertible
protocol still expects a urlRequest
property that returns the constructed request, so we can't just call encode
and return the result, nor return a nil.
What is the suggested way of handling this, if the router can't fail?
That's how Alamofire handles it internally :
open func request(
_ urlString: URLStringConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> DataRequest
{
let urlRequest = URLRequest(urlString: urlString, method: method, headers: headers)
do {
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return request(resource: encodedURLRequest)
} catch {
let request = self.request(resource: urlRequest)
request.delegate.error = error
return request
}
}
Basically, it uses the request without the parameters. I don't know how far it can be used in your own implementation (or How to migrate Alamofire router class to Swift 3? 's OP).
I'd suggest filing an issue with Alamofire if this is not possible. The new ParameterEncoding
is literally two days old (PR 1465) and still in the 4.0.0 beta cycle.
In any case, using URLEncoding.encode()
seldom fails if you set your own URLRequest
because the only error thrown is when there's no URL provided with the request.
EDIT: Here you go, 4.0.0 released, and the issue's been fixed! (PR 1505). There have been other changes to URLRequestConvertible
but all's in the Migration Guide and README.