Sam
Sam

Reputation: 137

Firebase how to get NSDictionary data

I would like to get some data in user profile, I've got some info but I got stuck at this one.

Firebase database: enter image description here

Here is some of my code:

self.ref.child("users").child("profile").observe(.childAdded, with: { (snapshot) in


        if let dictionary = snapshot.value as? [String:Any] {

            let user = User()

            let brands = dictionary["status"] as! NSDictionary


            user.displayname = dictionary["displayname"] as? String
            user.isconnected = brands["isconnected"] as? String

            print(user.isconnected) //fatal error: unexpectedly found nil while unwrapping an Optional value


class User: NSObject {
    var displayname: String?
    var isconnected: String?
}

Upvotes: 0

Views: 957

Answers (1)

Pipiks
Pipiks

Reputation: 2048

Try something like that :

guard let dictionary = snapshot.value as? [String: Any] else {
    return
}

guard let statusDictionary = dictionary["status"] as? [String: Any] else {
    return
}

guard let deviceStatusDictionary = statusDictionary["DEVICE_KEY"] as? [String: Any] else {
    return
}

let user = User()

user.displayname = dictionary["displayname"] as? String
user.isconnected = deviceStatusDictionary["isconnected"] as? Bool

You need to know your device key.

And :

class User: NSObject {
    var displayname: String?
    var isconnected: Bool?
}

Upvotes: 1

Related Questions