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

tsn*_*iso 0 post swift moya

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

我怎样才能做到这一点?

我的帖子 json 正文是这样的:

[
    {
        "UserId" : "14224",
        "CustomerId" : "16695",
        "ProductCode": "1",
        "Quantity":"2"
    },
    {
        "UserId" : "14224",
        "CustomerId" : "16695",
        "ProductCode": "2",
        "Quantity":"3"
    }
]
Run Code Online (Sandbox Code Playgroud)

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

小智 7

  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
}
Run Code Online (Sandbox Code Playgroud)
  1. 您需要创建一个服务
enum MyService {
  case postUsers(users: [User])
}
Run Code Online (Sandbox Code Playgroud)
  1. 你需要让你的服务符合TargetType协议
enum MyService {
  case postUsers(users: [User])
}
Run Code Online (Sandbox Code Playgroud)
  1. 最后您可以执行 POST 网络请求。
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"]
    }
}

Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档