在Alamofire POST请求中将数组作为参数发送 [英] Send an array as a parameter in a Alamofire POST request

查看:2475
本文介绍了在Alamofire POST请求中将数组作为参数发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用目前正在使用AWS API Gateway和Alamofire来访问充当我后端的不同lambda函数。

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

我需要将一个数组作为参数之一发送到其中一个API端点,因为我使用以下代码:

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

但由于数组未被识别,因此无效API,但如果我创建一个静态数组

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

一切都按预期工作。

我如何解决这种情况,因为感兴趣的数组来自代码的另一部分,我应该如何声明或构建它?

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?

朋友管理在Android中使用

A friend managed to accomplish this in Android using an

ArrayList<String>

编辑:

打印参数数组告诉我这个:

Printing the parameters array shows me this:

["name":test, "interests": <_TtCs21_SwiftDeferredNSArray 0x7b05ac00>( 103, 651, 42), "lastName": test]


推荐答案

AnyObject只能代表类类型。在Swift中,Array和Dictionary是struct,而不是许多其他语言中的类类型。结构不能被描述为AnyObject,这就是Any进来的原因。除了类之外,Any也可以在所有其他类型中使用,包括struct和enum。

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.

因此,每当我们输入强制转换数组或字典到AnyObject _TtCs21_SwiftDeferredNSArray时发生错误。所以我们必须使用Any而不是AnyObject。

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
    ]

这篇关于在Alamofire POST请求中将数组作为参数发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆