Encode Swift array for Alamofire post using URLEncoding

Viewed 3780

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?

5 Answers

As of now you can use for this & issue on parameters:

let enc = URLEncoding(arrayEncoding: .noBrackets)
Alamofire.request(url, method: .get, parameters: parameters, encoding: enc)

You can use URLEncoding.default for .get httpMethod, and JSONEncoding.default for other httpMethods ex: .post, .delete, .put

AF.request( url,
            method: httpMethod ,
            parameters: parameters,
            encoding: httpMethod == .get ? URLEncoding.default : JSONEncoding.default,
            headers: headers )
    .responseJSON(completionHandler: {})

Also, you can set httpHeaders content type based on httpMethod as the following code:

    enum RequestContentType: String {
        case json = "application/json"
        case urlEncoded  = "application/x-www-form-urlencoded"
        case multipart = "multipart/form-data"
    }
                
    let headers :HTTPHeaders  = [ 
                "Content-Type" : httpMethod == .get ? contentType : RequestContentType.json.rawValue 
// add other parameters here ...
            ]
Related