2

I'm using Alamofire to call .put method on an external API. In Postman I can successfully pass raw JSON data in the following format where each item contains an ID and a quantity. :

[{
    "id":"176",
    "quantity":"2"
}, {
    "id":"178",
    "quantity":"1"
}]

cURL example:

PUT /cart HTTP/1.1
Host: someapi.biz
x-api-key: somekey
x-auth-token: sometoken
Content-Type: application/json
cache-control: no-cache
Postman-Token: sometoken
[{
    "id":"176",
    "quantity":"2"
}, {
    "id":"178",
    "quantity":"1"
}]------WebKitFormBoundary7MA4YWxkTrZu0gW--

In swift I can't figure out how to format this information correctly into a set of Parameters for Alamofire.

    for item in OrderedItems {
                let rowItem: JSON = ["id" : item.ID, "quantity" : item.Quantity]
??
}
1
  • for the same key of parameter, you want to send then used multipart format of Alomofire . Commented Oct 15, 2018 at 6:21

1 Answer 1

5

Check below code:

var arrParam = [Any]()
    for item in OrderedItems
    {
        let rowItem: JSON = ["id" : item.ID, "quantity" : item.Quantity]
        arrTemp.append(rowItem)
    }

    // Convert Array into JSON String (Raw)
    guard let data = try? JSONSerialization.data(withJSONObject: arrParam, options: []) else {
        return
    }
    let paramString = String(data: data, encoding: String.Encoding.utf8)

    var request = URLRequest(url: URL(string: "URL")!)
    request.httpMethod = HTTPMethod.put.rawValue
    request.httpBody = paramString?.data(using: .utf8)

    Alamofire.request(request).responseJSON { (response) in

    }

Hope this will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

this worked perfectly. Thank for you helping clarify this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.