0

I'm trying to make a put request with Alamofire and I want to pass in body something like this:

[
   {
    "id" : 1,
    "position": 0
   },
   {
    "id" : 2,
    "position": 1
   },
   {
    "id" : 6,
    "position": 2
   }
]

Normally, to do a request with alamofire I do this:

request = Alamofire
                .request(
                    url,
                    method: method,
                    parameters: parameters,
                    encoding: encoding,
                    headers: buildHeaders()); 

Alamofire forces me to make parameters a dictionary but I want that paramaters to be an array of dictonary. How can I do this?

Thanks.

2 Answers2

1

Well, the body of your parameters has type as [[String: Any]], or if you using Alamofire [Parameters].

So you if you parsing some Array of Objects to create this Array of parameters. You can do like this:

var positionedArray = [[String : Any]]()
        for (index, item) in dataArray.enumerated() {
            guard let id = item.id else {
                return
            }
            let singleParameters : [String: Any] = ["id": id, "position" : index]
            sorted.append(singleParameters)
        }

As result, you can use this body (parameters), for your request. Also, you should use JSONSerialization:

For example, if you using a customized Alamofire client, just use extension:

let data = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
                let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
                var finalRequest = try URLEncoding.default.encode(request, with: nil)
1

Alamofire added support for Encodable parameters in Alamofire 5, which provides support for Array parameters. Updating to that version will let you use Array parameters directly. This support should be automatic when passing Array parameters, you just need to make sure to use the version of request using encoder rather than encoding if you're customizing the encoding.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37