Send an array as a parameter in a Alamofire POST request

試著忘記壹切 提交于 2019-12-08 23:33:29

问题


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]

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



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



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



回答4:


let ValueArray = ["userid": name,"password":password]

pass ValueArray [parameters: ValueArray] also verify the encoding accepted by the API.




回答5:


It turned out to be a problem with duplicated ids in the array. The code behind the API threw an exception that was not being send back as an error.

All the other answers are correct, I tested them after finding the problem and everything worked so I am going to up-vote them.

Thank you very much.



来源:https://stackoverflow.com/questions/36563371/send-an-array-as-a-parameter-in-a-alamofire-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!