gpt4 book ai didi

ios - 如何从 firebase 数据库检索特定值并将其分配给 Swift 4 中的特定变量?

转载 作者:行者123 更新时间:2023-11-29 05:33:27 26 4
gpt4 key购买 nike

我在 firebase 中有一个数据库,如下所示: enter image description here

我需要获取 nameID、tutorID 和 imageURL 的值,并将它们分配给 Swift 4 中的变量。这是到目前为止我在 XCode 中得到的:

let ref = Database.database().reference().child("students").child("student1")
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot)
guard let dictionary = snapshot.value as? [String : AnyObject] else {
return
}
print (dictionary)
let Obj = studentInformation(nameID: " ", tutorID: " ", imageURL: " ")
Obj.imageURL = dictionary["photoID"] as? String
Obj.nameID = dictionary["nameID"] as? String
Obj.tutorID = dictionary["tutorID"] as? String
self.studentInfo.append(Obj)
}, withCancel: nil)

对于 StudentInformation 类,我已将其声明为:

class studentInformation {
var nameID: String?
var tutorID: String?
var imageURL: String?

init(nameID: String?, tutorID: String?, imageURL: String?) {
self.nameID = nameID
self.tutorID = tutorID
self.imageURL = imageURL
}
}

我似乎无法让它正常工作,因为它能够从数据库获取值,但它无法将其分配给我在 XCode 中的局部变量。任何帮助,将不胜感激。提前致谢

最佳答案

在对象中创建一个可选的初始值设定项,并确定哪些变量应该是可选的(例如:在下面的示例中,只有 imageURL 是可选的,nameIDtutorID 必须是字符串,否则 init 将返回 nil):

init?(dictionary: [String : Any]) {

guard let nameId = dictionary["nameID"] as? String,
let tutorID = dictionary["tutorID"] as? String else { return nil }

let imageURL = dictionary["imageURL"] as? String

self.init(nameID: nameID, tutorID: tutorID, imageURL: imageURL)

}

然后,在 Firebase 监听器中,您可以像这样创建对象:

// Returns Optional(obj)
let obj = studentInformation(dictionary: dictionary)

// Add object to array
if let obj = studentInformation(dictionary: dictionary) { self.studentInfo.append(obj) }

关于ios - 如何从 firebase 数据库检索特定值并将其分配给 Swift 4 中的特定变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57313607/

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