Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...