尝试从Firebase Swift获取数据

时间:2018-10-24 14:22:43

标签: ios swift firebase firebase-realtime-database

好吧,我有一个函数,它必须找到等级的平均值,因此我将等级的总数和等级的总和存储在我的Firebase中(可以正常工作)。我正在尝试检索数据,但似乎它甚至都没有输入.observeSingleEvent的代码块。在尝试更新值时,我使用的是相同的方法,这意味着我得到了它们,并为其添加了新的评分然后使用下面的代码更新值:

let ratingObject = [
   "uid" : (user?.uid)! as String,
   "totalRatings" : newRating as Int,
   "amountOfRatings" : newAmountOfRating as int
   ] as [String : Any]

dbRef.setValue(ratingObject)

它没有给出错误,我只是迷路了

我尝试根据以下教程进行操作:https://www.youtube.com/watch?v=JV9Oqyle3iE

此线程中给出的答案:how parsing Firebase FDatasnapshot json data in swift只是使应用程序崩溃了

private func FindAverage(uid: String) -> Int {

    var totalRatings = 0
    var amountOfRatings = 1
    let dbRef = Database.database().reference().child("ratings").child(uid)

    dbRef.observeSingleEvent(of: .value, with: { snapshot in

        let dict = snapshot.value as? [String:Any]
        totalRatings = dict?["totalRatings"] as? Int ??  0
        amountOfRatings = dict?["amountOfRatings"] as? Int ??  1

    }){ (error) in
        print(error.localizedDescription)
    }

    return((Int)(totalRatings/amountOfRatings))
}

数据库结构 enter image description here

任何提示和帮助都非常感谢!

2 个答案:

答案 0 :(得分:1)

您正在尝试从完成处理程序中返回值。

您的功能应类似于:

private func findAverage(byUid uid: String, completion: @escaping (_ average: Int) -> Void) {
    // ...
    dbRef.observeSingleEvent(of: .value, with: { snapshot in
        guard let dict = snapshot.value as? [String: Any] else {
            return
        }
        totalRatings = dict["totalRatings"] as? Int ?? 0
        amountOfRatings = dict["amountOfRatings"] as? Int ?? 1

        completion((Int)(totalRatings / amountOfRatings))
    })
}

类似这样的内容,请检查Swift文档(有关完成处理程序等)。

答案 1 :(得分:0)

尝试以下代码:

private func FindAverage(uid: String) -> Int {
  var totalRatings = 0
  var amountOfRatings = 1
  let dbRef = Database.database().reference().child("ratings").child(uid)
  dbRef.observeSingleEvent(of: .value, with: { snapshot in
     if snapshot.exists() {
        guard let dict = snapshot.value as? [String: Any] else {
           return
        }
        totalRatings = dict?["totalRatings"] as? Int ??  0
        amountOfRatings = dict?["amountOfRatings"] as? Int ??  1
     }
   }){ (error) in
      print(error.localizedDescription)
   }
   return((Int)(totalRatings/amountOfRatings))
}