Home > Mobile >  Swift how to Create Multipage Form and Save Data to Firebase?
Swift how to Create Multipage Form and Save Data to Firebase?

Time:03-19

I have successfully installed Firebase and connected the login and registration with UID. If the user saves additional data in the app, I would now like to assign this to the respective user who is logged in, what is the best way to do this? Sorry I'm a beginner in Swift and Firebase, I need a tutorial or an explanation that is not too complex.

Thank you all

  • Uikit
  • Swift 5
  • Firebase

CodePudding user response:

All of this is assuming you have Firebase UserAuth connected with your app and setup.

All users have a UID, user identifier, that uniquely identifies them. This is easy to get.

//there must be a user signed in
let user = Auth.auth().currentUser
let uid = user.uid

Simply put, to store data that is unique to the user, store it all under the uid using Firestore. If you do not have Firestore, get started with Firestore.

All data you save to Firestore, must be structured in a dictionary format with String as the key and Any as the value. For example, if I wanted to store the top 3 favorite flavors of ice cream for a user, you would do this *note firebase will create these documents and collections for you automatically if they do not exist so do not panic *:

//First get a reference to the database.
// It is best to have db as a global variable
let db = Firestore.firestore()
let favoriteFlavors: [String: Any] = ["numberOne":flavorOne as Any, "numberTwo":flavorTwo as Any, "numberThree": flavorThree as Any]

//access the collection of users
//access the collection of the currentUser
//create a document called favoriteFlavors
//set the document's data to the dictionary
db.collection("users").collection(uid).document("favoriteFlavors").setData(favoriteFlavors) { err in
    if let err = err {
        print("Error writing document: \(err)")
    } else {
        print("Document successfully written!")
    }
}

Now, when you want to retrieve this data, you do access the users collection, the collection of the logged in user, then read the favoriteFlavors document--like this:

let docRef = db.collection("users").collection(uid).document("favoriteFlavors")

docRef.getDocument { (document, error) in
    if let document = document {
        print("Document received")
// retrieve the data in the document (a dictionary)
        let data = document.data()

    } else {
        print("Document does not exist")
    }
}

So if you wanted to get the number one favorite flavor, you would do this:

//Remember that data is a dictionary of String:Any
if let numberOneFlavor = data["numberOne"] as? String {
    print("Number one favorite flavor ",numberOneFlavor)
}

Granted, this can get more convoluted, but this is a solid foundation of what you need to know. I advice reading the add data and get data pages of the Firestore documentation.

  • Related