gpt4 book ai didi

swift - 如何解析来自 firebase 的数据,然后将其保存在模型中。 Swift3 MVC 格式

转载 作者:行者123 更新时间:2023-11-30 12:16:33 25 4
gpt4 key购买 nike

我的 firebaseDB 中有一个用户类。它是您所期望的平面文件数据库的样子:用户->UID->配置文件->键/值。我正在尝试在我的代码中实现最佳实践,因此我希望数据由 Xcode 项目中的用户模型处理。我将如何解析数据并将其保存为模型中的类变量。

class User {
private var _username: String
private var _uid: String

var uid: String {
return _uid
}


var username: String {
return _username
}


init (uid: String, username:String) {
self._uid = uid
self._username = username
}

func getUserData() {
DataService.ds.REF_USERS.observeSingleEvent(of: .value, with: { (snapshot) in
if let users = snapshot.value as? Dictionary<String, Any>{
for (key, value) in users { // We use the for in loop to iterate through each key/value pair in the database which is stored as a dictionary.
if let dict = value as? Dictionary<String, Any> { // This gets us inside the user ID
if let profile = dict["profile"] as? Dictionary<String, Any> { // This gets us inside the profile
if let username = profile["username"] as? String {
self._uid = key // Stores the UID of the user as the key.
self._username = username
} else {
let username = profile["name"] as? String
self._uid = key
self._username = username!
}
}
}

}
}

这就是我想要做的,但我不知道如何在类中实际存储数据值。仅供引用:用户名是配置文件下的一个属性。

最佳答案

您当前正在循环访问数据库中的整个用户列表并重复分配用户属性,从而覆盖上一个循环周期中的值。

为了获得分配的正确用户值,您需要一种了解值的正确路径的方法。我建议使用分配的 Firebase UID 保存用户。

如果您知道要查找的正确 UID,则可以实现以下代码:

func getUserData() {

DataService.ds.REF_USERS.child(_uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot) in
guard let profileDict = snapshot.value as? [String: Any] else {
print("Error fetching user")
return
}

self._username = profileDict["username"] as? String ?? profileDict["name"] as! String

})
}

在原始代码中强制解开“用户名”的方式似乎并不安全,但我假设您确信它会成功。否则,应更改以下行以安全地解开可选内容:

self._username = profileDict["username"] as? String ?? profileDict["name"] as! String

关于swift - 如何解析来自 firebase 的数据,然后将其保存在模型中。 Swift3 MVC 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45363211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com