代码之家  ›  专栏  ›  技术社区  ›  PvDev

如何获取iOS Swift中使用FireStore的用户数

  •  0
  • PvDev  · 技术社区  · 7 年前

    我已经将用户帖子、追随者和追随者从FireBase迁移到FireStore。现在,我已经迁移了帖子、追随者、跟踪者和帖子,追随者也算在内。

    这里是我从FireBase迁移到FireStore的代码。

    <预> <代码>导入基础 导入FireBaseDatabase 导入FireBaseFireStore 类FollowAPI{ var ref_followers=database.database().reference().child(“followers”)。 var ref_following=database.database().reference().child(“following”)。 设db=firestore.firestore()。 func followaction(具有用户ID:string){ 让docref=db.collection(“用户日志”).document(id) 中的docref.getdocument(document,error) 如果让document=document,document.exists{ 让datadescription=document.data().map(string.init(describing:)??“无” 打印(“文档数据\(数据描述)”) self.db.collection(“feed”).document(api.user.current_用户!.uid).setdata([document.documentid:true]) }其他{ 打印(“文档不存在”) } } self.db.collection(“followers”).document(id).setdata([api.user.current_user!.uid:正确]) self.db.collection(“following”).document(api.user.current_用户!.uid).updatedata([id:true]) } func unfollowaction(具有用户ID:string){ 让docref=db.collection(“用户日志”).document(id) 中的docref.getdocument(document,error) 如果让document=document,document.exists{ 让datadescription=document.data().map(string.init(describing:)??“无” 打印(“文档数据\(数据描述)”) self.db.collection(“feed”).document(api.user.current_用户!.uid).delete()。 }其他{ 打印(“文档不存在”) } } self.db.collection(“followers”).document(id).setdata([api.user.current_user!.uid:nsnull()]) self.db.collection(“following”).document(api.user.current_用户!.uid).setdata([id:nsnull()]) } func如下(userid:string,已完成:@escaping(bool)->void){ 让docref=db.collection(“followers”).document(userid) 中的docref.getdocument(document,error) 如果让document=document,document.exists{ print(“documnetdata:::\(string(describing:document.data()))”) 如果让datadescription=document.data(),则让=datadescription[api.user.current_user!.uid]作为?布尔{ 已完成(真) } 已完成(错误) }其他{ 已完成(错误) } } } func fetchcountfollowing(userid:string,完成时间:@escaping(int)->void){ //引用.child(userid).observe(.value,with:){ //快照在 //让count=int(snapshot.childrencount) //完成(计数) //}) 中的db.collection(“following”).document(userid).getdocument(querysnapshot,error) 让count=int((querysnapshot?.documentid)!) print(“followingcount:::\(string(describing:count))”) 完成(计数!) } } }//跟随API

    
    

    我尝试从Firestore获取以下计数。

    let count=int((querysnapshot?.documentid)!)
    print(“followingcount:::\(string(describing:count))”)
    完成(计数!)
    

    但还没有全部显示出来。我不知道我犯了什么错误?

    任何帮助都非常感谢,请…..

    这里是我从FireBase迁移到FireStore的代码。

     import Foundation
    import FirebaseDatabase
     import FirebaseFirestore
    
    class FollowApi {
    
    
    var REF_FOLLOWERS = Database.database().reference().child("followers")
    var REF_FOLLOWING = Database.database().reference().child("following")
    let db = Firestore.firestore()
    
    func followAction(withUser id: String) {
    
    
        let docRef = db.collection("user-posts").document(id)
    
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
    
                self.db.collection("feed").document(API.User.CURRENT_USER!.uid).setData([document.documentID: true])
    
            } else {
                print("Document does not exist")
            }
        }
    
    
    
       self.db.collection("followers").document(id).setData([API.User.CURRENT_USER!.uid: true])
       self.db.collection("following").document(API.User.CURRENT_USER!.uid).updateData([id: true])
    
    }
    
    func unFollowAction(withUser id: String) {
    
        let docRef = db.collection("user-posts").document(id)
    
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
    
    
    
     self.db.collection("feed").document(API.User.CURRENT_USER!.uid).delete()
    
    
            } else {
                print("Document does not exist")
            }
        }
    
    
    
        self.db.collection("followers").document(id).setData([API.User.CURRENT_USER!.uid: NSNull()])
        self.db.collection("following").document(API.User.CURRENT_USER!.uid).setData([id: NSNull()])
    
     }
    
    func isFollowing(userId: String, completed: @escaping (Bool) -> Void) {
    
        let docRef = db.collection("followers").document(userId)
    
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
    
                print("documnetData::::\(String(describing: document.data()))")
                if let dataDescription = document.data(), let _ = dataDescription[API.User.CURRENT_USER!.uid] as? Bool {
    
                    completed(true)
                }
    
                completed(false)
    
            } else {
               completed(false)
            }
        }
    
    
    }
    
    
    
    
    
        func fetchCountFollowing(userId: String, completion: @escaping (Int) -> Void) {
      //     REF_FOLLOWING.child(userId).observe(.value, with: {
      //                snapshot in
     //                let count = Int(snapshot.childrenCount)
     //                completion(count)
     //            })
    
    
    
            db.collection("following").document(userId).getDocument { (querySnapshot, error) in
    
                let count = Int((querySnapshot?.documentID)!)
                print("followingCount::::\(String(describing: count))")
                completion(count!)
            }
    
        }
    
     }//followAPI
    

    我试着从消防站得到以下数据。

      let count = Int((querySnapshot?.documentID)!)
                print("followingCount::::\(String(describing: count))")
                completion(count!)
    

    enter image description here

    但还没有全部显示出来。我不知道我犯了什么错误?

    非常感谢您的帮助,请……

    1 回复  |  直到 7 年前
        1
  •  1
  •   TheTiger    7 年前

    如果您正在查询 collection 那么它的 snapshot 将包含一个数组 documents .你想得到的是 documentID 这和 key 在里面 Firebase .

    消防库消防基地

    documentID=快照.key

    documentData=快照.value

    现在,到要点来,这里是你需要得到的计数。

    let count = querySnapshot?.documents.count
    print(count)
    

    编辑评论: 如何将ref_following.child(userid).observe(.value,with:snapshot in let count=int(snapshot.childrencount)completion(count))迁移到FireStore

    基于附加的数据库结构 following 对应于 userId 这是一个 Document .

    REF_FOLLOWING.document(userId).getDocument { (snapshot, error) in
        if let _error = error {
           print(_error.localizedDescription)
           return
        }
    
        guard let _snapshot = snapshot else {return}
    
        /// This is a single document and it will give you "[String:Any]" dictionary object. So simply getting its count is the result you needed.
        let dict = _snapshot.data()
        print(dict.count)
    }
    
    推荐文章