如何获取Firebase评级的平均值并将该评级添加到阵列

时间:2019-04-15 09:48:45

标签: arrays swift firebase firebase-realtime-database struct

因此,我有一个包含所有帖子数据的firebase数据结构,用户可以将帖子的评分从1-5分级,然后将该评分发布到firebase。我想从Firebase中获取所有评分,并获取平均值,然后将其显示在数组中。

这是我的数据库Json

 "-LcV8XRlEBg18Cv-ZwNb" : {
   "Ratings" : {
    "87YKrynk0cVrlb8JRdmhsIKbtiI3" : "3",
    "x578atznVfRSkHUsZjt1F5DYFHn2" : "5"
  },
  "Difficulty" : "Moderate",
  "Title" : "Video About Cats",
  "id" : "-LcV8XRlEBg18Cv-ZwNb",
  "url" : "https://firebasestorage.googleapis.com/v0/b/adventurisk.appspot.com/o/locationImages%2F-LcV8XRlEBg18Cv-ZwNb?alt=media&token=95ec0e63-2ffc-4089-880a-016d38935694"
}

这是我当前尝试从Firebase下载数据并将其附加到数组中的尝试

func downloadPosts() {
    ref = Database.database().reference()
    ref.child("location").observe(.childAdded) { (snapshot: DataSnapshot) in
        if let dict = snapshot.value as? [String:AnyObject] {
            let title = dict["Title"] as! String
            let key = dict["id"] as! String
            let rating = dict["Rating"] as! String
            let difficulty = dict["Difficulty"] as! String
            self.ref.child("location/\(key)/Ratings").observe(.value, with: { (snapshot: DataSnapshot) in
                for childSnap in snapshot.children.allObjects {
                    let snap = childSnap as! DataSnapshot
                    let rating = snap.value as! String


                }
            })



            self.arrAllPosts.insert(infoWindowStruct(title: title, rating: rating, key: key, diff: difficulty), at: 0)
        }
    }
}

但是,这只是获取了整个数据库的所有评分,我只希望与每个帖子相关的评分。在此示例中,该值为3和5的平均值。子键只是UID。

0 个答案:

没有答案