Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST multiple json objects in Alamofire POST method - Swift/IOS

Sorry if my question is not clear, I'll try to make myself clear with an explanation. So here is exactly what I'm trying to do, I'm trying to use Alamofire to post more than one comment (Something that my app implements and will be stored as a JSON object whenever user writes a new comment). I'm passing these JSON comments to my post routine, where I can use SwiftyJSON to extract each value. Noe the thing is I know how to set the parameters if I'm trying to authorize the user as follows,

    var parameters = [
    "userName": userName,
    "password": passwordSalt,
    "somethingElse": somethingElse
    ]
    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters , options: nil, error: &err)

it's quite straightforward until here, now comes my problem. I'm trying to use alamofire post to post multiple json objects, which should look like this

[
   {
    "comment": "my First Comment",
    "commentDate": "2014-05-13 14:30 PM",
    "isSigned": 1,
    "patientId": 2,
    "documentId": 3
    },
   {
    "comment": "my SecondComment",
    "commentDate": "2014-05-14 14:30 PM",
    "isSigned": 2,
    "patientId": 3,
    "documentId": 4
    },
   {
    "comment": "my third Comment",
    "commentDate": "2014-05-15 14:30 PM",
    "isSigned": 3,
    "patientId": 4,
    "documentId": 5
    }
 ]

How do I create above array/json (I'm not exactly sure on what to call this) by iterating JSON object? I know how to get the JSON values from the JSON object all I'm asking is how to create this parameters variable to hold the data like above example. Is it even possible to do this using Alamofire? (POST multiple objects at once)

I tried a couple of ways to but they didn't work out

  1. var dictArray = [Dictionary<String, Any>]
    var dict = Dictionary<String, Any>
    

    While iterating over JSON object inserted each value in dict and appended dict to dictArray, now when I'm trying to use dictArray as parameters in .dataWithJSONObject it doesn't like the object.

  2. var dict = Dictionary<String, AnyObject>
    var array = NSArray()
    

    extracted each value by iterating over the JSON object and inserted them into dict and tried inserting dict into array. But this gives a different problem. The way it builds the objects is different from what is required, as follows.

    [
       {
        comment: my First Comment,
        commentDate: 2015-05-13 13:30 PM"",
        isSigned: 1,
        patientId: 2,
        documentId: 3 
       },
       {
        comment: my Second Comment,
        commentDate: 2015-05-13 13:30 PM"",
        isSigned: 2,
        patientId: 5,
        documentId: 4 
       },
       {
        comment: my third Comment,
        commentDate: 2015-06-13 13:30 PM"",
        isSigned: 5,
        patientId: 1,
        documentId: 9 
       }
    ]
    

    Here the Keys doesn't get wrapped inside quotes (Correct way: "comment", wrong way: comment).

Did anyone try posting multiple objects, is alamofire capable of doing so? I hope I made the question clear. Sorry if this is too simple of a question to answer, I spent my whole day figuring this out but didn't work out.

like image 325
Sashi Avatar asked Apr 28 '15 04:04

Sashi


1 Answers

The correct representation in Swift for the array of comment objects you have posted would be like this:

    let comments: Array<[String:AnyObject]> = [
        [
            "comment": "my First Comment",
            "commentDate": "2014-05-13 14:30 PM",
            "isSigned": 1,
            "patientId": 2,
            "documentId": 3
        ],
        [
            "comment": "my SecondComment",
            "commentDate": "2014-05-14 14:30 PM",
            "isSigned": 2,
            "patientId": 3,
            "documentId": 4
        ],
        [
            "comment": "my third Comment",
            "commentDate": "2014-05-15 14:30 PM",
            "isSigned": 3,
            "patientId": 4,
            "documentId": 5
        ]
    ]

Sending a single comment would be fairly simple:

    let comment: [String:AnyObject] = [
        "comment": "my First Comment",
        "commentDate": "2014-05-13 14:30 PM",
        "isSigned": 1,
        "patientId": 2,
        "documentId": 3
    ]

    Alamofire.request(.POST, "http://httpbin.org/post", parameters: comment).responseJSON { (req, res, json, error) in
        println(req)
        println(res)
        println(json)
        println(error)
    }

However, in order to send an array of comments, seems like you would have to generate the URLRequest your self and then pass it to Alamofire as follows:

    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "http://httpbin.org/post")!)
    mutableURLRequest.HTTPMethod = "POST"
    var error: NSError? = nil

    let options = NSJSONWritingOptions.allZeros
    if let data = NSJSONSerialization.dataWithJSONObject(comments, options: options, error: &error) {
        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        mutableURLRequest.HTTPBody = data
    }

    Alamofire.request(mutableURLRequest).responseJSON { (req, res, json, error) in
        println(req)
        println(res)
        println(json)
        println(error)
    }

If you could modify the API backend to accept an object with multiple comments, you could also send them this way:

    Alamofire.request(.POST, "http://httpbin.org/post", parameters: ["comments": comments]).responseJSON { (req, res, json, error) in
        println(req)
        println(res)
        println(json)
        println(error)
    }

Regards.

like image 169
Eneko Alonso Avatar answered Sep 28 '22 09:09

Eneko Alonso