gpt4 book ai didi

Swift Firebase 读取一个 child 的 child

转载 作者:行者123 更新时间:2023-11-28 10:12:15 25 4
gpt4 key购买 nike

所以我正在尝试读取下面“Recipes”下面的 autoID 子项的子项是我的 Firebase 数据库的图片,下面是应该检索“Description”和“Name”的值并插入的方法它们变成变量。

我目前在运行该应用程序时遇到的错误是:

Could not cast value of type '__NSCFString' (0x10ad2afb8) to 'NSDictionary' (0x10ad2bfa8).

My Firebase database

    ref = Database.database().reference()

databaseHandle = ref?.child("Recipes").observe(.childAdded) { (snapshot) in

for snap in snapshot.children
{
let recipeSnap = snap as! DataSnapshot
let recipeID = recipeSnap.key
let dict = recipeSnap.value as! [String:AnyObject]
let recipeName = dict["Name"] as! String
let recipeDescription = dict["Description"] as! String
print("key = \(recipeID) and name = \(recipeName) and description = \(recipeDescription)")
}
}

打印语句只是为了测试。

最佳答案

请尝试以下操作,如果现在有效,请告诉我:

// SEARCHES FOR SHARING CODE IN DATABASE (ONLINE)
let parentRef = Database.database().reference().child("Recipes")

parentRef.observeSingleEvent(of: .value, with: { snapshot in

// SHOWING WHATEVER WAS RECEIVED FROM THE SERVER JUST AS A CONFIRMATION. FEEL FREE TO DELETE THIS LINE.
print(snapshot)

// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {

// DATA WAS NOT FOUND
print("– – – Data was not found – – –")

} else {

// DATA WAS FOUND
for user_child in (snapshot.children) {

let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]

// DEFINE VARIABLES FOR LABELS
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
print("– – – Data for the recipe \(recipeName) with the description \(recipeDescription) was found successfully! – – –")
}
}
}

如果您只想检索一个特定食谱的名称和描述,您应该将第三行更改为

parentRef.queryEqual(toValue:DefineWhatToSearchForHere).observeSingleEvent(of: .value, with: { snapshot in

如果您不断想要更新以反射(reflect)更改,您可以使用计时器每 x 秒调用此函数并将其添加到 override func viewDidLoad() 中,例如

time = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(ViewController.updateFBData), userInfo: nil, repeats: true)

在创建一个名为 func updateFBData() 的函数之后,您可以在其中做任何您想做的事情来获取新数据(见上文)并在定义的 timeInterval 中调用它

或者您可以做 Attila Hegedüs in this excellent tutorial.

关于Swift Firebase 读取一个 child 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487024/

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