Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...