从Firebase Swift读取数据 [英] Read data from firebase swift

查看:70
本文介绍了从Firebase Swift读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Firebase数据库检索数据,但是当我运行代码时,它什么也没有显示,尽管没有显示错误

I'm trying to retrieve data from firebase database, but when I run the code it display nothing, though no errors shown

顺便说一句,我从Firebase手册中获得了这段代码,我很确定路径是正确的

I got this piece of code from Firebase manual, by the way, I'm pretty sure that the path is correct

let ref = FIRDatabase.database().reference()

ref.child("users").child("user").child(username).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let score = value?["score"] as? String ?? ""
        print(score)

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

JSON

{
  "users" : {
    "user" : {
      "e1410kokeZS8xv81J1RzhN4V2852" : {
        "email" : "aaaa@gmail.com",
        "score" : 0,
        "username" : "Afnan"
      },
      "jPx8XJ3Q9AazDM7qIOhz02PBfh22" : {
        "email" : "aaaa@ggg.com",
        "score" : 13,
        "username" : "ghhh"
      }
    }
  }
}

推荐答案

您正在监听.value事件,但是您的块一次只处理一个项目,因此请使用.childAdded事件.

You are listening for the .value event, but your block is dealing with a single item at a time so use .childAdded event for that.

let ref = FIRDatabase.database().reference().child("users").child("user").child(username)

ref.observeSingleEvent(of: .childAdded, with: { (snapshot) in
     if let userDict = snapshot.value as? [String:Any] {
          //Do not cast print it directly may be score is Int not string
          print(userDict["score"]) 
     }
}

注意:在Swift中,使用本机Dictionary代替NSDictionary

Note: In Swift use native Dictionary instead of NSDictionary

这篇关于从Firebase Swift读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆