【问题标题】:want to fetch userdata from firebase into a dictionary想要从 firebase 获取用户数据到字典中
【发布时间】:2017-08-16 14:12:33
【问题描述】:

我希望你能帮助我: 我尝试将用户数据从 firebase 数据库提取到用户类中并调用“setValuesForKeys”。我确实知道我的类属性必须与 firebase 字典中的完全一样,但我收到错误“此类不符合关键城市的键值编码。”

func fetchUsers(){
    Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
        if let usersDictionary = snapshot.value as? [String: String] {
            let users = Userdata()
            users.setValuesForKeys(usersDictionary)
        }
    }, withCancel: nil)
}

我的用户类是

class Userdata: NSObject {
    var email: String?
    var password: String?
    var firstname: String?
    var lastname: String?
    var street: String?
    var streetno: String?
    var zipcode: String?
    var city: String?
    var phone: String?  }

firebase 的快照看起来像

Snap (ndLBXXX75Oe9Y1PXrqfISL8A4v82) {
city = Washington;
email = "1@a.com";
firstname = Andre;
lastname = Doe;
password = xxxxxx;
phone = "";
street = "Mainstreet";
streetno = 1;
zipcode = 11111;

}

数据库中的字典看起来像

["city": Washington, "firstname": Andre, "lastname": Doe, "email": 1@a.com, "password": xxxxxx, "streetno": 1, "phone": , "street": Mainstreet, "zipcode": 11111]

到目前为止,我有一个解决方案:

users.city = dictionary["city"]

我的问题/问题:我确实想了解错误消息“此类不符合关键城市的键值编码”背后的问题。因为类和 firebase 快照中的密钥看起来相同。

【问题讨论】:

标签: swift dictionary firebase firebase-realtime-database


【解决方案1】:

工作解决方案:我必须扩展我的用户类。现在,整个用户类看起来像:

代码如下:

 import Foundation

    class UserData: NSObject {
        var id: String?
        var email: String?
        var password: String?
        var salutation: String?
        var degree: String?
        var firstname: String?
        var lastname: String?
        var street: String?
        var streetno: String?
        var zipcode: String?
        var city: String?
        var phone: String?
        var profileImage: String?

    init(dictionary: [String: Any]) {
        self.city = dictionary["city"] as? String
        self.id = dictionary["id"] as? String
        self.email = dictionary["email"] as? String
        self.salutation = dictionary["salutation"] as? String
        self.degree = dictionary["degree"] as? String
        self.firstname = dictionary["firstname"] as? String
        self.lastname = dictionary["lastname"] as? String
        self.password = dictionary["password"] as? String
        self.phone = dictionary["phone"] as? String
        self.street = dictionary["street"] as? String
        self.streetno = dictionary["streetno"] as? String
        self.zipcode = dictionary["zipcode"] as? String
        self.profileImage = dictionary["profileImage"] as? String

    }
}

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 2019-12-26
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多