swiftpostmoya

How to post an array of objects with moya library?


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


Solution

    1. You need to a model for the object you want to post
    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
    }
    
    1. You need to create a service
    enum MyService {
      case postUsers(users: [User])
    }
    
    1. You need to make your service conform the TargetType protocol
    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"]
        }
    }
    
    
    1. Finally you can perform your POST network request.
    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.