Search code examples
swiftuiswiftui-form

How do I send user inputs to a database using the forms feature in swift UI?


I’m new to swift UI and programming in general. I’ve learnt the basics so far and now I want to be able to setup a simple form in my app. I can design the form no problem. But I’m not sure what function to call CIA the button action or the code to get that information from the user to a database. Can someone help to explain how to set that up and which database to use to collect the user information?


Solution

  • I can't set the database up for you, as each database has its unique ways of doing so. However, I am giving you a basic structure that would help you link your SwiftUI view to the back-end(your database).

    Setting up your form

    import SwiftUI
    
    struct ContentView: View {
        @State var firstName = ""
        @State var lastName = ""
        @State var age = ""
        
        var body: some View {
            TextField("Enter First Name", text: $firstName)
            TextField("Enter Last Name", text: $lastName)
            TextField("Age", text: $age)
            Button(action: {
                addUser(firstName: firstName, lastName: lastName, age: Int(age) ?? 0)
            }) {
                Text("Save to database")
            }
        }
    }
    

    Saving result to back-end:

    import CoreData
    
    func addUser(firstName: String, lastName: String, age: Int) {
    /*   
         code here would be using Core Data structure
         do not copy paste, only used as reference
    */
        let newUser = User(context: context)
        newUser.firstName = firstName
        newUser.lastName = lastName
        newUser.age = age
        
        do {
            try context.save()
            print("Successfully saved to Core Data.")
        } catch {
            print(error.localizedDescription)
        }
        
    }
    

    Keep in mind that you would have to do your own research on how to save results using your own database. The code in addUser() would not work if you are using something other than Core Data. In your case, I would suggest you to try Firebase and perhaps, you could use Firebase Firestore as it seems like it suits your needs.