如何解析firebase实时数据库

时间:2022-10-29 13:06:18

How I can parse firebase realtime database?

我如何解析firebase实时数据库?

So far my code is:

到目前为止我的代码是:

var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
   print("snapshot = \(snapshot)")
}

I can not enter the condition. 如何解析firebase实时数据库

我不能进入这个条件。

print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"

this variant don't work too

这种变体也不起作用

var ref: DatabaseReference!
    ref = Database.database().reference().child("data")

    ref.observeSingleEvent(of: .value) { (snapshot) in
        for data in snapshot.children {
            print("data = \(data)")
        }
    }

1 个解决方案

#1


0  

To reference the official docs -

参考官方文档 -

refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})

You want to be looking for the snapshot.value not snapshot.children

您想要查找snapshot.value而不是snapshot.children

A further example

另一个例子

let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)

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

also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.

此外,.childAdded仅在添加子项时触发。 IE,在您实际更改该节点引用中的某些内容之前不会发生任何事情。

#1


0  

To reference the official docs -

参考官方文档 -

refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
  let postDict = snapshot.value as? [String : AnyObject] ?? [:]
  // ...
})

You want to be looking for the snapshot.value not snapshot.children

您想要查找snapshot.value而不是snapshot.children

A further example

另一个例子

let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
  // Get user value
  let value = snapshot.value as? NSDictionary
  let username = value?["username"] as? String ?? ""
  let user = User(username: username)

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

also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.

此外,.childAdded仅在添加子项时触发。 IE,在您实际更改该节点引用中的某些内容之前不会发生任何事情。