如何在swift中发布嵌套数据



用户结构:

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": ?....]

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

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

现在使用此data作为URLRequesthttpBody,即

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])

相关内容

  • 没有找到相关文章

最新更新