Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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())
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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())
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...