1

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

enter image description here

reference.child("doc1").observe(.value, with: { (snapshot) in
            if snapshot.exists() {
                for date in (snapshot.value?.allKeys)
            }
aofdev
  • 1,772
  • 1
  • 15
  • 29
iX0ness
  • 123
  • 9
  • What was the error ? – Surjeet Singh Sep 21 '17 at 12:42
  • The problem was in casting, it should be casted to Any?. I've fixed it, doing smth like this: for date in ((snapshot.value as AnyObject).allKeys) { self.workDays.append(snapshot.value as! String) } print(self.workDays) And now i get an error in console : "Could not cast value of type '__NSDictionaryM' (0x11191f218) to 'NSString' (0x110d5dd68)." – iX0ness Sep 21 '17 at 12:58

1 Answers1

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  
}
Giuseppe Sapienza
  • 4,101
  • 22
  • 23