如何快速获取 Firebase 数据作为模型?

问题描述

我正在尝试从 firebase 获取数据并将其用作我创建的模型。

这是我的模型;

class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}

class Competition{
    var end_date : String = ""
    var gift : String = ""
    var id: String = ""
    var name: String = ""
    var users : [String:Int] = [:]
}

这是我的功能;

func getFirebaseData() {
    ref = Database.database().reference()
    ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { (snapshot) in
        if let snapshotValue = snapshot.value as? Dictionary<String,Any> {
            
            //change userData with the snapshotValue
            self.userData.nickname = snapshotValue["nickname"] as! String
            self.userData.step_count = snapshotValue["step_count"] as! Int
            self.userData.total_point = snapshotValue["total_point"] as! Int
            self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
            self.userData.competitions = snapshotValue["competitions"] as! [String:Competition]
            //reload UI with userData

            print(self.userData.competitions)
            
        } else {
            print("An error occured while assigning snapshotValue to userData")
        }
    }
}

这段代码给了我这样的错误;

无法将“__NSDictionaryM”(0x1f47ada20)类型的值转换为“StepCounterApp.Competition”(0x1004c06f0)。 2021-01-02 23:05:49.985711+0300 StepCounterApp[32511:3685645] 无法将“__NSDictionaryM”(0x1f47ada20)类型的值转换为“StepCounterApp.Competition”(0x1004c)。0x1004c

但是当我从 self.userData.competitions 函数中注释掉包含 getFirebaseData 的行时,一切正常。

我该怎么办?如何将 Firebase 数据用作模型?

最后是我的 firebase 数据;

Firebase data

解决方法

问题出在您的数据模型中。像这样声明你的模型数据

class UserData {
    var nickname : String = ""
    var onesignal_player_id : String = ""
    var step_count : Int = 0
    var total_point : Int = 0
    var competitions : Competition = Competition()
}

class Competition{
    var end_date : String = ""
    var gift : String = ""
    var id: String = ""
    var name: String = ""
    var users : [String:Int] = [:]
    
    init() {
    }
    
    init(with dictionary: [String: Any]) {
        self.end_date = dictionary["end_date"] as! String
        self.gift = dictionary["gift"] as! String
        self.id = dictionary["id"] as! String
        self.name = dictionary["name"] as! String
        self.users = dictionary["users"] as! [String:Int]
    }
}

getFirebaseData 函数内部

self.userData.competitions = Competition(with: snapshotValue["competitions"] as! [String: Any])
,

问题出在我的数据模型中,在 Raja Kishan 的数据模型建议的帮助下,我解决了这个问题。

首先我稍微改变了模型;

class UserData{
    var nickname : String = ""
    var onesignal_player_id : String = ""
    var step_count : Int = 0
    var total_point : Int = 0
    var competitions : [String:Competition] = [String:Competition]()
}

class Competition{
    var end_date : String = ""
    var gift : String = ""
    var id: Int = 0
    var name: String = ""
    var users : [String:Int] = [:]

    init() {
    }

    init(with dictionary: [String: Any]) {
        self.end_date = dictionary["end_date"] as! String
        self.gift = dictionary["gift"] as! String
        self.id = dictionary["id"] as! Int
        self.name = dictionary["name"] as! String
        self.users = dictionary["users"] as! [String:Int]
    }
}

然后我在我的方法中添加了一个 childSnapshot,这样我就可以直接处理“比赛”;

func getFirebaseData() {
    ref = Database.database().reference()
    ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { [self] (snapshot) in
        if let snapshotValue = snapshot.value as? [String:Any] {
            
            //change userData with the snapshotValue
            self.userData.nickname = snapshotValue["nickname"] as! String
            self.userData.step_count = snapshotValue["step_count"] as! Int
            self.userData.total_point = snapshotValue["total_point"] as! Int
            self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
            
            //******
            //This part of the coded added for to solve the problem starting from here 
            let childSnap = snapshot.childSnapshot(forPath: "competitions")
            if let childSnapValue = childSnap.value as? [String:Any] {
                childSnapValue.forEach { (element) in
                    self.userData.competitions.updateValue(Competition(with: element.value as! [String:Any]),forKey: element.key)
                }
            } else {
                print("something wrong with the childSnap")
            }
            //to here
            //******

        } else {
            print("An error occured while assigning snapshotValue to userData")
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...