Creating a router using Alamofire to handle my API requests like so:
enum GoogleRouter: URLRequestConvertible {
case FetchCoordinatesFromPostcode(postcode: String)
static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json?"
var method: HTTPMethod {
switch self {
case .FetchCoordinatesFromPostcode:
return .get
}
}
var path: String {
switch self {
case .FetchCoordinatesFromPostcode(let postcode):
return "?address=\(postcode)&key=MY_KEY"
}
}
func asURLRequest() throws -> URLRequest {
let url = try GoogleRouter.baseURLString.asURL()
print(url)
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
default:
break
}
return urlRequest
}
}
Problem is that, the URL to fetch the lat long from the postcode I'm entering has a ?
in the middle of the URL. No matter where I seem to place the question mark, whether at the end of the baseURLString
or the beginning of the path
, the ?
seems to become encoding thus sending a request to the wrong url (I've inserted both in the code above)
How can I get around this?
try it like this
enum GoogleRouter: URLRequestConvertible {
//the base url (REMOVE THE ? MARK)
static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json"
//the router
case FetchCoordinatesFromPostcode([String:Any]) //set the case like this
var method: HTTPMethod {
switch self {
case .FetchCoordinatesFromPostcode:
return .get
}
}
//WE Won't be needing path, so lets just remove it
/*var path: String {
switch self {
case .FetchCoordinatesFromPostcode(let postcode):
return "?address=\(postcode)&key=MY_KEY"
}
}*/
func asURLRequest() throws -> URLRequest {
//get the url from string
let url = try GoogleRouter.baseURLString.asURL()
//prepare urlrequest
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
switch self {
case .FetchCoordinatesFromPostcode(let parameters):
urlRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
}
return urlRequest
}
}
func testCall() {
let parameters = ["addres":"myAddress","key":"MY_KEY"]
let request = Alamofire.request(GoogleRouter.FetchCoordinatesFromPostcode(parameters))
request.validate().responseJSON { (response) in
//Do The Thing
}
}