How to post Nested Data in swift?

Viewed 70

User Struct:

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

UserDocument Struct:

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

Document Struct:

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?
}

And This is Request Body (I'm stuck here):

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

Since you're using Codable, you can simply encode your User instance using JSONEncoder's encode(_:) method.

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

Now use this data as httpBody of URLRequest, i.e.

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
        //...
    }
}

Edit:

Assuming the User object is like,

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