微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何快速发布嵌套数据?

如何解决如何快速发布嵌套数据?

用户结构:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。