TIMEX
TIMEX

Reputation: 272304

How do I turn a Firebase snapshot into an array of items?

{ 
    "body": "Hello there",
    "viewers": {
        "1": {
            "user_id": 1
        },
        "2":{
            "user_id": 2
        }
    }
}

Above is the snapshot I received from Firebase.

        fireRef!.observeEventType(FEventType.Value) { [weak self] (snapshot: FDataSnapshot!) -> Void in
            if let stuff = snapshot.value as? [String:AnyObject] {
                print(stuff) //okay, it prints the snapshot correctly
                //Now, I need to access the "viewers" part, but how?
            }
        }

How can I loop through each viewer and print the user ID?

Upvotes: 1

Views: 590

Answers (1)

BergerBytes
BergerBytes

Reputation: 397

Popped open my last project with Firebase, I was solving this problem as follows:

if let viewers = stuff["viewers"] as? [String:[String:Int]] { //Firebase could deliver your numbers as strings, in that case try [String:[String:String]]
                for viewer in viewers {
                    let userID = viewer.1
                    print(userID.values.first)
                }
            }

There could be a cleaner way to do it

Upvotes: 1

Related Questions