Swift 在Alamofire中使用之前对URL进行编码

Swift 在Alamofire中使用之前对URL进行编码,swift,swift4,Swift,Swift4,现在我正在用参数发出Alamofire请求。在发出请求之前,我需要最终URL,因为我需要散列最终URL并将其添加到请求头中。我就是这样做的,但它并没有给我最终的URL进行散列并放入一个标题中 Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON 我想在发出此请求之前获取编码的URL,因此请求如下所示 Al

现在我正在用参数发出Alamofire请求。在发出请求之前,我需要最终URL,因为我需要散列最终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)"

您可以使用它来轻松地添加URL参数等等,而不是“手边”编写自己的URL

下面是使用上面的URL的示例:

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
,但至少你不必再费劲按正确的顺序添加
&


希望这对您有所帮助。

您可以用它来轻松添加URL参数等,而不是“在手”编写自己的URL

下面是使用上面的URL的示例:

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
,但至少你不必再费劲按正确的顺序添加
&


希望对您有所帮助。

这里有一个简洁的函数,用于将字典参数转换为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)
这将为您提供输出:


这里有一个简洁的函数,用于将字典参数转换为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)
这将为您提供输出:


这太棒了!为什么要在已经是字符串的项目周围加“/”?@NevinJethmalani是对的:)
URLComponents
是一个很好的URL工具。关于“在()中包装字符串”,对不起…复制粘贴:)我现在已经更改了,这太棒了!为什么要在已经是字符串的项目周围加“/”?@NevinJethmalani是对的:)
URLComponents
是一个很好的URL工具。关于“在()中包装字符串”,对不起…复制粘贴:)我现在已经更改了