Search code examples
swifturlutf-8alamofire

Alamofire dealing with special character parameters


the ServiceKey I got for the api is mixed with complex characters, like D%2FFgugDIl1le9xiY7be1ge%2B0Q%3D%3D

and when I put the key in the params of alamofire and use the .get keyword, my key transforms and when the url is actually created, it becomes a totally different key.

is there any way to solve this problem?

This is the code I am using

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)
            }
    }

Solution

  • Try below:

    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)
                }
            })
    

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