Send an array as a parameter in a Alamofire POST request

15,687

Solution 1

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
    ]

Solution 2

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

Solution 3

The problem is that you have just declared the array and not initialized it. That makes the interest array as nil even if u try to insert the data. Try writing

var interests = [String]()

instead of

var interests : [String]
Share:
15,687
ur3k
Author by

ur3k

Updated on June 29, 2022

Comments

  • ur3k
    ur3k 3 months

    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]
    
  • ur3k
    ur3k over 6 years
    This is indeed the way the parameters array is constructed but the problem comes when trying to send an array as one of those parameters, when working only with strings everything is fine.
  • oyalhi
    oyalhi over 6 years
    How did you solve this problem? It's not a problem of duplicate entries. I also get the same result as you. "People": <_TtCs21_SwiftDeferredNSArray 0x7f7f565d1440>( 3, 23105 ).
  • ur3k
    ur3k over 6 years
    In my case the problem was on the server side and not an Alamofire problem. I would recommend you open a new question with more details about what is going on.
  • Admin
    Admin over 2 years
    request.setValue("application/json;charset=UTF-8",forHTTPHea‌​derField:"Content-Ty‌​pe")