0

Here is the code

struct URLParameterEncoder: ParameterEncoderProtocol {

    /// Takes dictionary parameters and encode them to make them safe to be passed as URLQueryItem in the URLRequest
    func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {

        guard let url = urlRequest.url else {throw ParameterEncoderError.missingURL}

        //Only execute if there are parameters to encode
        if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {

            urlComponents.queryItems = [URLQueryItem]()

            for (key,value) in parameters {
                let queryItem = URLQueryItem(name: key, value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))

                urlComponents.queryItems?.append(queryItem)
            }

            printLog("url before query items ", urlRequest.url!)

            urlRequest.url = urlComponents.url
        }
    }


}

Although the URLItem gives right output. But when it is added to URL component, it gives this result.

https://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%2520sys
 - scheme : “https”
 - host : “xxxxxxxxx.net”
 - path : “/api/v1/merchant/list”
 ▿ queryItems : 3 elements
  ▿ 0 : q=filter
   - name : “q”
   ▿ value : Optional<String>
    - some : “filter”
  ▿ 1 : showRPPS=true
   - name : “showRPPS”
   ▿ value : Optional<String>
    - some : “true”
  ▿ 2 : industry=insurance%20sys
   - name : “industry”
   ▿ value : Optional<String>
    - some : “insurance%20sys”

Required : https://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%20sys

Actual : https://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%2520sys

Himan Dhawan
  • 864
  • 5
  • 19

1 Answers1

3

URLComponents adds percent encodings to its components when needed. You should not add percent encodings manually.

            for (key,value) in parameters {
                let queryItem = URLQueryItem(name: key, value: String(describing: value))

                urlComponents.queryItems?.append(queryItem)
            }
OOPer
  • 44,179
  • 5
  • 90
  • 123