gpt4 book ai didi

ios - 在 Alamofire POST 请求中发送一个数组作为参数

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:07 25 4
gpt4 key购买 nike

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

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

        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 无法识别该数组,但如果我创建一个“静态”数组

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

一切正常。

如果利益数组来自代码的另一部分,我该如何解决这种情况,我应该如何声明或构造它?

一位 friend 设法在 Android 中使用

ArrayList<String>

编辑:

打印参数数组向我展示了这一点:

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

最佳答案

通过使用 NSJSONSerialization 对 JSON 进行编码,您可以构建自己的 NSURLRequest 以在 Alamofire 中使用它,这是一个 Swift 3 示例:

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

关于ios - 在 Alamofire POST 请求中发送一个数组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com