How can i get only keys from firebase?

蹲街弑〆低调 提交于 2020-01-06 05:51:11

问题


I have a structure of database as on image and I need to display this date which is in the red rectangle. I tried to do smth like this, but it throws an error and I couldn't find same questions on a stack.

my database

reference.child("doc1").observe(.value, with: { (snapshot) in
            if snapshot.exists() {
                for date in (snapshot.value?.allKeys)
            }

回答1:


Your structure is a Dictionary of Dictionary so you have to cast your snap to [String:[String:Any]] where the key is your "11dot..." and value contains all hours

So try to use this code:

guard let dict = snap.value as? [String:[String:Any]] else { return }
for (key, value) in dict {
    for (key2, value2) in value {
        print(key2, value2) // this print your hours
    }
}

Anyway I suggest you to don't use a observe(.value) which will read all change happened on all child node. Instead use the .childAdded feature of observer.

With a .childAdded you will receive only one child at a time (like a for on child node) and after that only the child added:

Database.database().reference().child("doc1").observe(.childAdded) { (snap) in
    guard let dict = snap.value as? [String:Any]
    print(dict) // this print data contains on "11dot10" and so on  
}


来源:https://stackoverflow.com/questions/46343915/how-can-i-get-only-keys-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!