AppleBee
AppleBee

Reputation: 472

Custom URLEncoding for Alamofire

I am having issues with Alamofire URLEncoding, particularly, for array of parameters where the use [ ] separator for parse the array of parameters.

How can I write my own URLEncoding for this case?

Upvotes: 0

Views: 349

Answers (2)

Parimal
Parimal

Reputation: 277

Please use this string extension

 public extension String {
    public func URLEncode() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
      }
    }

Upvotes: 0

KKRocks
KKRocks

Reputation: 8322

Try this For Get:

struct CustomGetEncoding: ParameterEncoding {
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var request = try URLEncoding().encode(urlRequest, with: parameters)
            request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
            return request
        }
    }

How to use

 Alamofire.request("url", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding()).validate().responseJSON { (response) in

        }

Upvotes: 1

Related Questions