【问题标题】:How to post Nested Data in swift?如何快速发布嵌套数据?
【发布时间】:2020-08-31 13:16:16
【问题描述】:

用户结构:

struct User: Codable, Identifiable {
    let id = UUID()
    let userId: Int?
    let userName: String?
    let 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": ?....]

【问题讨论】:

    标签: swift httprequest codable


    【解决方案1】:

    由于您使用的是 Codable,您可以简单地使用 JSONEncoder's encode(_:) 方法对您的 User 实例进行编码。

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

    现在使用这个data 作为httpBodyURLRequest,即

    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 对象是这样的,

    let doc = Document(documentId: 0, ownerId: 0, secureName: "", title: "", description: "", fileExtension: "", fileSize: 200, url: "String?")
    let userDoc = UserDocument(userDocumentId: 0, userId: 0, documentId: 0, document: doc)
    var user = User(userId: 0, userName: "name", userDocument: [userDoc])
    

    【讨论】:

    • 谢谢你的回答,这部分没问题。我很抱歉没有添加。我不会写正文
    • @Robert 那你面临什么问题?
    • 我将普通结构添加到正文没有问题,但是当我尝试嵌套对象时,后操作失败。我想我拼错了body。我该如何编写这个示例正文?
    • @Robert 为什么在拥有User 实例时还要手动创建正文?你可以像我上面描述的那样直接使用它。
    • @PGDev 也许添加一个创建用户实例然后用.encode(user)对其进行编码的示例(我知道这应该很明显)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2016-08-15
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多