简体   繁体   中英

Convert array into Alamofire parameters in Swift

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]
??
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM