在 swift 中使用 alamofire 将参数作为原始数据发送
Posted
技术标签:
【中文标题】在 swift 中使用 alamofire 将参数作为原始数据发送【英文标题】:Send params as raw data using alamofire in swift 【发布时间】:2020-05-20 03:51:37 【问题描述】:在 swift 中使用 alamofire 时,我将以下原始数据作为参数发送
"customer":
"firstname": "test",
"lastname": "user",
"email": "testuser30@gmail.com",
"website_id": 1,
"addresses": [
"customer_id": 3292,
"region":
"region": "New York"
,
"country_id": "US",
"street": [
"US"
],
"telephone": "84656313",
"postcode": "34521",
"city": "us",
"firstname": "test",
"lastname": "usr",
"default_shipping": true,
"default_billing": true
]
我已经使用 alamofire 在代码中编写了如下给出的参数。
let customer : Parameters = [
"email":email,
"firstname":fname,
"lastname":lname,
"website_id":1,
"addresses":
[
"customer_id": id,
"region": [
"region": state
],
"country_id": country,
"street":
self.add1Txt.text! + self.add2Txt.text!
,
"telephone": self.phoneTxt.text!,
"postcode": self.pincodeTxt.text!,
"city": self.cityTxt.text!,
"firstname": self.fnameLbl.text!,
"lastname": self.lnameLbl.text!,
"default_shipping": true,
"default_billing": true
]
]
let parameters: Parameters =
[
"customer": customer
]
它显示“JSON 写入 (__SwiftValue) 中的类型无效”。这个参数传递有什么问题?
【问题讨论】:
【参考方案1】:您的客户变量不是正确的字典。 "addresses":
实际上是一个字典数组。它应该类似于以下代码。除此之外,如果您使用 Codable 创建模型结构并借助 JSONEncoder 和 JSONSerialization 转换为字典,则可以避免此类问题。你可以看到这个thread。
let parameters: Parameters = ["customer": [
"addresses" : [[
"city": "us",
"country_id" :"US",
"customer_id" :"3292",
"default_billing" : 1,
"default_shipping" : 1,
"firstname" :"test",
"lastname" :"usr",
"postcode" :34521,
"region" : ["region" : "New York"],
"street" : ["US"],
"telephone" : 84656313
]],
"email" : "testuser30@gmail.com",
"firstname": "test",
"lastname": "user",
"website_id" : 1
]]
【讨论】:
【参考方案2】:使用Quicktype 立即从您的 json 生成结构:
import Foundation
// MARK: - Parameters
struct Parameters: Codable
let customer: Customer?
// MARK: - Customer
struct Customer: Codable
let firstname, lastname, email: String?
let websiteID: Int?
let addresses: [Address]?
enum CodingKeys: String, CodingKey
case firstname, lastname, email
case websiteID = "website_id"
case addresses
// MARK: - Address
struct Address: Codable
let customerID: Int?
let region: Region?
let countryID: String?
let street: [String]?
let telephone, postcode, city, firstname: String?
let lastname: String?
let defaultShipping, defaultBilling: Bool?
enum CodingKeys: String, CodingKey
case customerID = "customer_id"
case region
case countryID = "country_id"
case street, telephone, postcode, city, firstname, lastname
case defaultShipping = "default_shipping"
case defaultBilling = "default_billing"
// MARK: - Region
struct Region: Codable
let region: String?
【讨论】:
以上是关于在 swift 中使用 alamofire 将参数作为原始数据发送的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 中使用 Alamofire 将参数作为正文发送到 PUT 方法
在 swift 中使用 alamofire 发送 JSON 数组作为参数
Swift 4:如何使用 Alamofire 在参数中发布文件?
如何在 Swift 中使用 Alamofire 上传带有 JSON 参数的图像?