如何使用moya库发布对象数组?

问题描述 投票:0回答:1

我想通过moya库发布对象的主体列表

我该怎么做?

我的帖子json主体是这样的:

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

请提供任何建议或示例代码?谢谢

swift post moya
1个回答
1
投票
  1. 您需要为要发布的对象建立模型
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

© www.soinside.com 2019 - 2024. All rights reserved.