Search code examples
iosswiftalamofire

Encode Swift array for Alamofire post using URLEncoding


Reposting as I messed up with the type of encoding before... I need to send an array to the server with Alamofire using URLEncoding. However, it needs to be encoded in some way for Alamofire to send it properly. This is my code:

let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }

However the parameters never get encoded and just get sent as nil. How can I encode it?


Solution

  • I solved it by using the following custom encoding:

    struct ArrayEncoding: 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
        }
    }
    

    The problem was the arrays were being encoded like foo[]=bar&foo[]=bar2 whereas my server needed it to look like foo=bar&foo=bar2. ArrayEncoding() then replaces URLEncoding.default in the request.