简体   繁体   中英

How to fetch data from Firebase Firestore by document ID - iOS?

How can I fetch data from Firebase Firestore, not by collection, but from current User (id). I have this code, but when I add "document(uid)", I get error message

"Cannot assign value of type 'DocumentReference' to type 'CollectionReference'"

private var collectionRef: CollectionReference!


override func viewDidLoad() {
    super.viewDidLoad()
    collectionRef = Firestore.firestore().collection("userInfo")  
} 

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
 
    
    collectionRef.getDocuments { (snapshot, error) in
        if let err = error {
            debugPrint("error fetching docs: \(err)")
        } else {
            guard let snap = snapshot else {
                return
            }
            for document in snap.documents {
                let data = document.data()
                let firstName = data[UserProfile.KEY_FIRST_NAME] as? String
                let secondName = data[UserProfile.KEY_SECOND_NAME] as? String
                
                
                self.namesLabel.text = firstName! + secondName!
                
                print(document.data())
            }
        }
    }
}

You are trying to read the information as soon as the view fires up on viewWillAppear , while you wait for viewDidLoad to set the collection path in which the information should be retrieved from, basically do this:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)


    collectionRef = Firestore.firestore().collection("userInfo")  // This line
    collectionRef.getDocuments { (snapshot, error) in
        if let err = error {
            debugPrint("error fetching docs: \(err)")
        } else {
            guard let snap = snapshot else {
                return
            }
            for document in snap.documents {
                let data = document.data()
                let firstName = data[UserProfile.KEY_FIRST_NAME] as? String
                let secondName = data[UserProfile.KEY_SECOND_NAME] as? String
                
                
                self.namesLabel.text = firstName! + secondName!
                
                print(document.data())
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM