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:
- Changing the code to check for the document each time a user logs in (though I worry about duplication or overwriting as blank)
- Building in a check to see if the document exists and only creating it if it does not
- Building in a retry
- 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.