I'm currently developing the registration feature for my SwiftUI app and need to send user registration data, including a profile image selected by the user, to my Vapor server. I've heard that using multipart/form-data is the best approach for this, but I'm relatively new to Swift and unsure about its implementation.
I'm using the this library (https://github.com/mridruejo5/MRNetwork.git) for networking tasks. How can I extend this library to support sending both the image and JSON data together? Is multipart/form-data the most suitable option for this scenario?
Additionally, I'm seeking guidance on handling this data on the server side. What would be the appropriate approach to receive and store this combined data in my Vapor application? Below is the current implementation of my create function in Vapor:
func create(req: Request) async throws -> HTTPStatus {
try Users.Create.validate(content: req)
let user = try req.content.decode(Users.Create.self)
guard let APIKey = Data(base64Encoded: user.APIKey),
APIKey == Data(AK) else {
throw Abort(.badRequest, reason: "Invalid user request.")
}
guard user.password == user.repeatPassword else {
throw Abort(.badRequest, reason: "Passwords do not match.")
}
let existingUsername = try await Users.query(on: req.db)
.filter(\.$username == user.username)
.first()
guard existingUsername == nil else {
throw Abort(.badRequest, reason: "Username not valid.")
}
let newUser = Users(name: user.name,
username: user.username,
email: user.email,
password: try Bcrypt.hash("\(user.username):\(user.password)"), termsConditions: user.termsConditions)
try await newUser.save(on: req.db)
if let existingUser = try await Users.query(on: req.db)
.filter(\.$username == user.username)
.first() {
let newProfile = Profiles(profileImage: user.profileImage, averageRating: user.rating, user: try existingUser.requireID())
try await existingUser.$profile.create(newProfile, on: req.db)
}
return .created
}
I have searched in multiple places online, but due to my short knowledge on the matter I haven't been able to completely grasp and understand the correct way to complete this procedure. I feel like I understand the general functioning of multipart/form-data but not exactly how to implement it in my case.