我想通过moya库发布对象的主体列表
我该怎么做?
我的帖子json主体是这样的:
[
{
"UserId" : "14224",
"CustomerId" : "16695",
"ProductCode": "1",
"Quantity":"2"
},
{
"UserId" : "14224",
"CustomerId" : "16695",
"ProductCode": "2",
"Quantity":"3"
}
]
请提供任何建议或示例代码?谢谢
struct User: Codable {
private enum CodingKeys: String, CodingKey {
case userID = "UserId"
case customerID = "CustomerId"
case productCode = "ProductCode"
case quantity = "Quantity"
}
let userID: String
let customerID: String
let productCode: String
let quantity: String
}
enum MyService {
case postUsers(users: [User])
}
TargetType
协议extension MyService: TargetType {
var baseURL: URL { return URL(string: "https://test.com")! }
var path: String {
switch self {
case .postUsers(let users):
return "/users"
}
}
var method: Moya.Method {
switch self {
case .postUsers:
return .post
}
}
var task: Task {
switch self {
case .postUsers(let posts):
return .requestJSONEncodable(posts)
}
}
var sampleData: Data {
switch self {
case .postUsers:
return Data() // if you don't need mocking
}
}
var headers: [String: String]? {
// probably the same for all requests?
return ["Content-type": "application/json; charset=UTF-8"]
}
}
let usersToPost: [User] = // fill this array
let provider = MoyaProvider<MyService>()
provider.request(.postUsers(users: usersToPost) { result in
// do something with the result (read on for more details)
}
有关更多信息,请查看documentation。