在Alamofire中使用之前编码URL

时间:2017-12-18 20:29:07

标签: swift swift4

现在我正在使用参数发出Alamofire请求。在请求发出之前我需要最终的URL,因为我需要散列最终的URL并将其添加到请求标头中。这就是我这样做的方式,但它没有给我最后的哈希值并放入标题。

Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON

我想在发出此请求之前获取编码的URL,因此请求看起来像这样

Alamofire.request(url, method: .get, headers: headers).responseJSON

现在作为一种解决方法,我通过手动附加每个参数手动创建URL。有没有更好的方法呢?

let rexUrl = "https://www.google.com"
let requestPath = "/accounts"
let url = rexUrl + requestPath + "?apikey=\(apiKey)&market=USD&quantity=\(amount)&rate=\(price)&nonce=\(Date().timeIntervalSince1970)"

2 个答案:

答案 0 :(得分:3)

您可以使用URLComponents轻松添加网址参数,而不是自己编写自己的网址。

以下是使用上述网址的示例:

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

当然,它不会让你的生活变得那么容易,因为你仍然需要自己写URL,但至少你不必为添加&和{{1}而努力以正确的顺序再次出现。

希望对你有所帮助。

答案 1 :(得分:0)

这是一个将Dictionary参数转换为URL编码字符串的简洁功能。但是你必须把你的参数放到一个字典中。

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
}

然后你可以像那样使用它

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)

这将为您提供输出:

https://www.google.com/accounts?apikey=SomeFancyKey&quantity=10&market=USD&nonce=1513630655.88432&rate=3