Alamofire处理特殊字符参数

时间:2018-09-14 09:05:01

标签: swift url utf-8 alamofire

我为api获取的ServiceKey包含了复杂的字符,例如D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D

然后,当我将密钥放入alamofire的参数中并使用.get关键字时,我的密钥就会转换,并且在实际创建url时,它将变成完全不同的密钥。

有什么办法可以解决这个问题?

这是我正在使用的代码

Alamofire.request(BusURL, method: .get, parameters: ["cityCode": 25, "routeId":"DJB30300052ND", "ServiceKey": key])
        .responseString { response in
            print(" - API url: \(String(describing: response.request!))")   // original url request
            var statusCode = response.response?.statusCode

            switch response.result {
            case .success:
                print("status code is: \(String(describing: statusCode))")
                if let string = response.result.value {
                    print("XML: \(string)")
                }
            case .failure(let error):
                statusCode = error._code // statusCode private
                print("status code is: \(String(describing: statusCode))")
                print(error)
            }
    }

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

let params = ["cityCode": "25", "routeId":"DJB30300052ND"]
        var urlParams = params.flatMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }).joined(separator: "&")

        let key = "&ServiceKey=D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D"
        urlParams.append(key)

        let url = "https://google.com?\(urlParams)"
        print("url\(url)")
        Alamofire.request(url, method: .get).validate().responseString(completionHandler: {response in
            switch response.result{
            case .success:
                let s = response.result.value ?? "Empty Result"
                print("response \(s)")
            case .failure:
                print("Call Failed")
                debugPrint(response)
            }
        })

输出:https://google.com?cityCode=25&routeId=DJB30300052ND&ServiceKey=D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D