如何使用 moya 库 post objects 的数组?

How to post an array of objects with moya library?

我想 post body objects 列表与 moya 库

我该怎么做?

我的postjsonbody是这样的:

[
    {
        "UserId" : "14224",
        "CustomerId" : "16695",
        "ProductCode": "1",
        "Quantity":"2"
    },
    {
        "UserId" : "14224",
        "CustomerId" : "16695",
        "ProductCode": "2",
        "Quantity":"3"
    }
]

有什么建议或示例代码吗? 谢谢

  1. 你需要一个你想要的对象的模型 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. 您需要创建一个服务
enum MyService {
  case postUsers(users: [User])
}
  1. 您需要让您的服务符合 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"]
    }
}

  1. 您终于可以执行 POST 网络请求了。
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