Search code examples
swiftgoogle-cloud-firestore

Creating a document for each user in firestore using swiftUI


My swiftUI app creates a new 'favourites' Firestore document for each new user (authenticated with Firebase Auth) after they sign up.

I currently do this with the code:

if let authResult = result, authResult.additionalUserInfo?.isNewUser == true {
                        //New user, create Favourites
                        self.createFavourites()
                               } else {
                                   // Existing user
                               }

Which eventually calls a function to create a document:

func createCollection(userID: String, name: String, description: String, isPublic: Bool, completion: @escaping (Error?) -> Void){
        let privateCollectionsRef = Firestore.firestore().collection("users").document(userID).collection("private_collections")
        
        let newCollectionData = [
            "name": name,
            "description": description,
            "date": Date(),
            //"isPublic": isPublic,
            "favourites": [:]  // Starting with an empty map of favourites
        ] as [String : Any]

        privateCollectionsRef.addDocument(data: newCollectionData) { error in
            if let error = error {
                print("Error creating collection: \(error.localizedDescription)")
                completion(error)
            } else {
                print("Collection created successfully.")
                completion(nil)
            }
        }
    }

But I'm worried about the impact of network connectivity interrupting the creation of the document.

For that reason, I've considered:

  1. Changing the code to check for the document each time a user logs in (though I worry about duplication or overwriting as blank)
  2. Building in a check to see if the document exists and only creating it if it does not
  3. Building in a retry
  4. Setting a userDefaults flag on success to prevent subsequent attempts at creation

But no matter how I do it, I'm worried about either failure to read the existing document before creating it, or failure to create it on the first attempt.

Am I missing something? For example, will the firestore cache hold the document even if the write fails, and return it when the relevant getDocuments function is called?

Appreciate any steer on this.


Solution

  • I'm worried about the impact of network connectivity interrupting the creation of the document

    You shouldn't worry about that.

    If the app loses connectivity, by default, the write will still happen locally in the Firestore SDK persistence layer (you should carefully read that page of docs), and you will be able to read it back locally while offline. Then, when connectivity returns, the document will be eventually written by the SDK, including any retries necessary to do so. The SDK will not simply lose data due to connectivity problems.

    (The only exception to this is if the document data you provide is somehow invalid, for example, violating a security rule that you define. That write might fail, and you might not know about it.)