用户结构:
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's
encode(_:)
方法对User
实例进行编码。
let data = try? JSONEncoder().encode(user) //user is the instance of User
现在使用此data
作为URLRequest
的httpBody
,即
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])