Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post array of objects with Alamofire and SwiftyJSON

I have an array of dictionaries that I am trying to post to Alamofire with the help of SwiftyJSON.

The api is set to take:

[
    {
        "imageUrl": "someimage3.jpg"
    },
    {
        "imageUrl": "someimage4.jpg"
    }
]

My array with image objects when printed out looks like this with the imageUrl key and image name for the value.

uploadedFiles = [
    [imageUrl: "someimage.jpg"],
    [imageUrl: "someimage2.jpg"]
]

I'm trying to convert the array of dictionaries into the format needed for the body. I'm not quite sure how to get them to be [String: AnyObject]

var body: [String: AnyObject] = [:]
let paramsJSON = JSON(uploadedFiles)
body = paramsJSON

alamofire post

Alamofire.request("\(BASE_URL)mainimages/\(someid)", method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseString { (response) in
        if response.result.error == nil {
            let status = response.response?.statusCode
            completion(true, status)
        } else {
            completion(false, nil)
            debugPrint(response.result.error as Any)
        }
    }
like image 514
Keith Avatar asked Apr 26 '18 05:04

Keith


1 Answers

You can achieve using this method, It worked for me.

let payload = [["eventName": "Notifications","body":["version": "1.0","latitude": lat,"longitude":lon]]] as [[String : AnyObject]]

trackEventRequest(requestParams: payload, urlString: "https://xyz/youyURL")





func trackEventRequest(requestParams: [[String: AnyObject]], urlString: String) {

        let url = URL(string: urlString)
        var request = URLRequest(url: url!)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: requestParams, options: [])

        Alamofire.request(reqeust).responseJSON { (response) in
            switch response.result {
            case .success:
                print(response.result.value)
                break
            case .failure:
                print(response.error)
                break
            }
        }
    }
like image 137
Purnendu roy Avatar answered Oct 20 '22 16:10

Purnendu roy