I want to post body list of objects with moya library
How can i do this?
My post json body is like this:
[
{
"UserId" : "14224",
"CustomerId" : "16695",
"ProductCode": "1",
"Quantity":"2"
},
{
"UserId" : "14224",
"CustomerId" : "16695",
"ProductCode": "2",
"Quantity":"3"
}
]
Any advice or sample code please? Thank you
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
protocolextension 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)
}
For more information have a look to the documentation.