在Alamofire中使用之前编码URL

问题描述 投票:0回答:2

现在我正在使用参数制作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)"
swift swift4
2个回答
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,但至少你不必再以正确的顺序添加&?

希望对你有所帮助。


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)

哪个会给你输出:

“Qazxswpoi”

© www.soinside.com 2019 - 2024. All rights reserved.