gpt4 book ai didi

swift - 如何在 alamofire 中将参数作为字符串发送

转载 作者:行者123 更新时间:2023-11-28 11:34:40 24 4
gpt4 key购买 nike

我必须接收指定我需要传递给 url 的负载的 JSON 数据。它看起来像这样:

{
"token": "string",
"body": {
"token": "another string",
"intValue": 1,
"somethingElse": "another string"
}
}

我知道 body 将具有始终为字符串或数字的属性。但我不知道与字符串或整数值配对的 key 是什么。

然后我需要用 Alamofire 发送那个 body ,我是这样做的:

// parsing the data received with the Codable:
struct NotificationDetails: Codable {
let token: String
let body: [String:String]?
let

init (token: String) {
self.token = token
self.body = nil
}

init (token: String, body: [String:String]) {
self.token = token
self.body = body
}

}

请注意,我不能只使用 Alamofire 方便的参数类型,例如:

struct NotificationDetails: Codable {
let token: String
let body: Parameters?

init (token: String) {
self.token = token
self.body = nil
}

init (token: String, body: Parameters) {
self.token = token
self.body = body
}
}

因为那是不可编码的,就像 AnyObject 一样。

// then elsewhere, using that data
guard let bodyJSON = localNotificationDetails.body else {
callback()
return
}
AF.request(url, method:method, parameters: bodyJSON).responseJSON(queue: queue) { response in

但现在我看到我的一些数据将是数字而不是字符串,我想知道我现在该如何做到这一点?

最佳答案

使用 bodyJson : [String : AnyObject]?

例子

let bodyJson = [
"key" : "value",
"key" : value,
"token": "string"
] as? [String : AnyObject]

在 json body 请求中传递这种类型的数据。

Alamofire.request(url, method: .post, parameters: bodyJson, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (responseObject) -> Void in

print(responseObject)
}

您可以对 responseObject 执行其他操作

关于swift - 如何在 alamofire 中将参数作为字符串发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840847/

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