Search code examples
swiftfirebasegoogle-cloud-firestorequeryingnested-documents

How to make app automatically recognise current user Firestore document ID when signed in?


When a user is signed up through my form, a document gets created associated with that user. My main goal is to create a global function that can recognize the user that is signed in and get their document ID. I have a function setup for adding documents to a subcollection of the user document which is perfectly setup, the only downfall is that when I'm testing with multiple accounts, I have to manually switch the collection path. Here is what I mean.

@IBAction public func createEventButton(_ sender: UIButton) {
    
    
    let error = validateFields()
    
    if error != nil {
        showError(error!)
    } else {
        
        db.collection("school_users/\(stThomas)/events").addDocument(data: ["event_name": nameTextField.text, "event_date": dateTextField.text, "event_cost": costTextField.text, "for_grades": gradesTextField.text]) { (error) in
            if error != nil {
                self.showError("There was an error trying to add user data to the system.")
            } else {
                self.dismiss(animated: true, completion: nil)
                
            }
        }
    }
    

So as you can see here, I am using string interpolation with the "stThomas" constant I used to store a document ID. I basically want to create a function that will recognize the document ID of the user signed in so I can use my Constants instead of string interpolation and having to manually switch the user collection path each time, which would be eventually impossible during production.

Not to mention, I do have a function to grab the document ID, say for instance an event is clicked, but as a beginner in Swift, I can't seem to connect the dots. I will also show this function for clarification.

 func getDocID() {
    db.collection("school_users/\(notreDame)/events").getDocuments() { (querySnapshot, error) in
        if let error = error {
            print("There was an error getting the documents: \(error)")
        } else {
            self.documentsID = querySnapshot!.documents.map { document in
                return DocID(docID: (document.documentID))
            }
            self.tableView.reloadData()
        }
    }
}

And in this function you can see my other constant "notreDame" with another stored document ID. If anybody knows a simple way to do this that would be great. And yes, I checked the Firebase documents, thank you for asking.


Solution

  • I've did some extra research and realized that I can use User IDs in collection paths. My problem is now solved. Many more problems to come though.