Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send an array as a parameter in a Alamofire POST request

My app is currently using AWS API Gateway and Alamofire to access different lambda functions that act as my backend.

I have the need to send an array as one of the parameters to one of those API end points, for that I am using the following code:

        var interests : [String]
        interests = globalInterests.map({ (interest) -> String in
            return interest.id!
        })

        // Parameters needed by the API
        let parameters: [String: AnyObject] = [
            "name" : name,
            "lastName" : lastName,
            "interests" : interests
        ]


        // Sends POST request to the AWS API
        Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON).responseJSON { response in

            // Process Response
            switch response.result {

            case .Success:

                print("Sucess")

            case .Failure(let error):
                 print(error)
            }
        }

But that is not working because of the array is not being recognized by the API, but if I create a "static" array

let interests = ["a", "b", "c"] 

Everything works as it is supposed to.

How can I fix this situation given that the array of interests come from another part of the code, how should I declare it or construct it?

A friend managed to accomplish this in Android using an

ArrayList<String>

EDIT:

Printing the parameters array shows me this:

["name":test, "interests": <_TtCs21_SwiftDeferredNSArray 0x7b05ac00>( 103, 651, 42), "lastName": test]
like image 608
ur3k Avatar asked Apr 12 '16 03:04

ur3k


2 Answers

By using NSJSONSerialization to encode JSON, you can build your own NSURLRequest for using it in Alamofire, here's a Swift 3 example:

    //creates the request        

    var request = URLRequest(url: try! "https://api.website.com/request".asURL())

    //some header examples

    request.httpMethod = "POST"
    request.setValue("Bearer ACCESS_TOKEN_HERE", 
                     forHTTPHeaderField: "Authorization")

    request.setValue("application/json", forHTTPHeaderField: "Accept")

    //parameter array

    let values = ["value1", "value2", "value3"]

    request.httpBody = try! JSONSerialization.data(withJSONObject: values)

    //now just use the request with Alamofire

    Alamofire.request(request).responseJSON { response in

        switch (response.result) {
        case .success:

            //success code here

        case .failure(let error):

            //failure code here
        }
    }
}
like image 67
mourodrigo Avatar answered Dec 02 '22 09:12

mourodrigo


AnyObject can only represent class type. In Swift, Array and Dictionary are struct, instead of the class type in many other languages. The struct cannot be described into AnyObject, and this is why Any comes in. Besides of class, Any can be utilized in all other types too, including struct and enum.

Therefore whenever we type cast array or dictionary to AnyObject _TtCs21_SwiftDeferredNSArray error occurs.So we have to Any instead of AnyObject.

    let parameters: [String: Any] = [
        "name" : name,
        "lastName" : lastName,
        "interests" : interests
    ]
like image 39
Aseem Aggawral Avatar answered Dec 02 '22 09:12

Aseem Aggawral