7

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.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Sashi
  • 533
  • 3
  • 6
  • 21

3 Answers3

5

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.

Eneko Alonso
  • 18,884
  • 9
  • 62
  • 84
  • I'm away from my system now, i will work on this whenever i can and let you know. Thanks for your time @Eneko :) – Sashi Apr 28 '15 at 04:47
0

This would be better

Create dictionary and array of dictionary var Then loop how many parameters you need to send from data source either an array or whatever.

Here my scenario

Need to answer to all questions (will be a random number/size)

var ansParams = [[String: String]]()
var paramz = [String: String]()


for question in sectionQuestions{
    paramz = [
        AppConstants.PARAMETER.KEY_1    : "Value",
        AppConstants.PARAMETER.KEY_2    : "Value",
        AppConstants.PARAMETER.KEY_3    : "Value",
        AppConstants.PARAMETER.KEY_4    : "Value",
        AppConstants.PARAMETER.KEY_5    : "Value"
    ]
    ansParams.append(paramz)
}


print(ansParams)


//Check All Paramz and its values then send ansParams as Parameter to POST request
iSrinivasan27
  • 1,406
  • 1
  • 21
  • 28
-2

I had a similar issue in my project while working with an API that did now allow posting multiple objects at once. The formatting of the array as noted above is fine.

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

Then I used a for loop to post each object of the array to post the API.

    var index = comments.count
    var i = 0

    for i = 0; i < index; i++ {

        let urlString = "\(.baseURL)...etc"

        let parameters = comments[i]

        Alamofire.request(.POST, urlString, parameters: parameters)

            .responseJSON { (req, res, data, error) -> Void in

//                    println(req)
//                    println(res)
//                    println(data)
//                    println(error)

                println("\(i) of \(index) posted")
        }
    }

More efficient ways if the API allows, but otherwise this flow works great.

hegranes
  • 97
  • 7