Reputation: 2826
Right now I am making an Alamofire request with parameters. I need the final URL before the request is made because I need to hash the final URL and add it to the request header. This is how I was doing it but it does not give me the final URL to hash and put into a header.
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON
I want to get the encoded URL before I make this request so the request looks like this
Alamofire.request(url, method: .get, headers: headers).responseJSON
Right now as a work around, I am creating the URL manually by appending each parameter manually. Is there a better way to do it?
let rexUrl = "https://www.google.com"
let requestPath = "/accounts"
let url = rexUrl + requestPath + "?apikey=\(apiKey)&market=USD&quantity=\(amount)&rate=\(price)&nonce=\(Date().timeIntervalSince1970)"
Upvotes: 0
Views: 2789
Reputation: 6876
Instead of writing your own URL "in hand" you can use URLComponents
to ease adding URL parameters and so on.
Here is an example using your URL from above:
var apiKey = "key-goes-here"
var amount = 10
var price = 20
var urlParameters = URLComponents(string: "https://google.com/")!
urlParameters.path = "/accounts"
urlParameters.queryItems = [
URLQueryItem(name: "apiKey", value: apiKey),
URLQueryItem(name: "market", value: "USD"),
URLQueryItem(name: "quantity", value: "\(amount)"),
URLQueryItem(name: "rate", value: "\(price)"),
URLQueryItem(name: "nonce", value: "\(Date().timeIntervalSince1970)")
]
urlParameters.url //Gives you a URL with the value https://google.com/accounts?apiKey=key-goes-here&market=USD&quantity=10&rate=20&nonce=1513630030.43938
Granted, it does not make your life that much easier as you still have to write the URL
yourself, but at least you don't have to wrestle with adding &
and ?
in the correct order anymore.
Hope that helps you.
Upvotes: 6
Reputation: 17
Here's a neat function for converting Dictionary parameters to a URL encoded string. But you'll have to put your parameters into a Dictionary.
func url(with baseUrl : String, path : String, parameters : [String : Any]) -> String? {
var parametersString = baseUrl + path + "?"
for (key, value) in parameters {
if let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),
let encodedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
parametersString.append(encodedKey + "=" + "\(encodedValue)" + "&")
} else {
print("Could not urlencode parameters")
return nil
}
}
parametersString.removeLast()
return parametersString
}
And then you can use it like that
let parameters : [String : Any] = ["apikey" : "SomeFancyKey",
"market" : "USD",
"quantity" : 10,
"rate" : 3,
"nonce" : Date().timeIntervalSince1970]
self.url(with: "https://www.google.com", path: "/accounts", parameters: parameters)
Which will give you the output:
Upvotes: 0