如何快速发布嵌套数据?

问题描述

用户结构:

struct User: Codable,Identifiable {
    let id = UUID()
    let userId: Int?
    let userName: String?
    let userDocument: [UserDocument]?
}

UserDocument结构:

struct UserDocument: Codable,Identifiable {
    let id = UUID()
    let userDocumentId: Int?
    let userId: Int?
    let documentId: Int?
    let document: Document?
}

文档结构:

struct Document: Codable {
    let documentId: Int
    let ownerId: Int?
    let secureName: String?
    let title: String?
    let description: String?
    let fileExtension: String?
    let fileSize: Int64?
    let url: String?
}

这是请求正文(我被卡在这里):

let body: [String: Any?] = ["userId": 0,"userName": "name","userDcuments": ?....]

解决方法

由于您使用的是 Codable ,因此您只需使用User JSONEncoder's encode(_:)实例进行编码方法。

let data = try? JSONEncoder().encode(user) //user is the instance of User

现在将此data用作httpBody的{​​{1}},即

URLRequest

编辑:

假设if let url = URL(string: "YOUR_URL") { var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = data //here... //rest of the request configurations.. URLSession.shared.dataTask(with: request) { (data,response,error) in //... } } 对象就像

User