用于从firebase实时数据库中提取数据的结构不再工作(新项目,但代码相同)



我有一个Firebase RTD设置,如下所示:

{
"D176" : {
"Phrase" : "Four score and seven years ago, our fore-fathers brought forth upon this continent, a new nation conceived in liberty...",
"Version" : "Abraham Lincoln"
},
"D177" : {
"Phrase" : "The acceptance of, and continuance hitherto in, the office to which your suffrages have twice called me...",
"Version" : "George Washington"
}
}

非常直接和简单的数据集。Test是父节点的名称,其中子节点用诸如D1、D2、D3等的字符串编码。在这些子节点中的每一个子节点中有两个被编码为"Test"的字符串;P〃;以及";V";分别地

我已经使用以下结构提取数据数百次,没有任何问题:

import Foundation
import Firebase
import FirebaseDatabase
struct FavItem {
let Phrase: String
let Version: String
let ref: DatabaseReference?

init(Phrase: String, Version: String) {
self.Phrase = Phrase
self.Version = Version
self.ref = nil
}

init(snapshot: DataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]

Phrase = snapshotValue["Phrase"] as! String
Version = snapshotValue["Version"]  as! String
ref = snapshot.ref
}

func toAnyObject() -> Any {
return [
"Phrase": Phrase,
"Version": Version
]
}
}

注意:是的,我知道Firebase声明也包括dB,但我将其添加为测试,目前尚未删除。

我在它自己的swift文件中定义了它,恰当地命名为";FavoriteItem.swift";。

以下是我用来提取数据的代码:

override func viewDidLoad() {
super.viewDidLoad()

intArray = defaults.array(forKey: "Favorites") as? [Int] ?? []
if intArray.count > 0 {
let myCount = intArray.count
for index in 1...myCount {
myCategory = "Test/D"
dbParm = myCategory + String(intArray[index - 1])
print(dbParm)
let myRef = myRef.reference(withPath: dbParm)
myRef.keepSynced(true)
// observe value of reference
myRef.observe(.value, with: {
snapshot in
var newItems: [FavItem] = []
for item in snapshot.children {
print(item)
let mItem = FavItem(snapshot: item as! DataSnapshot)
newItems.append(mItem)
}
self.items = newItems
//self.items.sort(by: {$0.key < $1.key})
newItems = self.items
self.tableView.reloadData()
print(newItems)

})
}
}
}

我使用的是一个从用户默认值构建的数组,用于代码(D1…(

当执行达到let mItem=FavItem(snapshot:item as!DataSnapshot(时,它会爆炸。

错误代码如下:

无法将"__NSCFString"类型的值(0x1f2585b40(强制转换为"NSDictionary"(0x1f25863d8(。2021-06-26 21:00:36.976208-0500 Bible[14649:3186734]无法将'__NSCFString'类型的值(0x1f2585b40(强制转换为'NSDictionary'(0x1f25863d8(。

这是我第一次遇到这个问题,坦率地说,这让我很困惑,因为我使用相同的例程从firebase中提取数据的次数不少于100次,没有失败。

有人知道为什么会发生这种事吗?我最初有D1,D2,。。。设置为Int;将其更改为字符串,希望能够解决问题,但错误完全相同。

据我所知,dbParm/myRef变量指向JSON中的特定子节点。例如,它可以指向D176,它具有以下JSON:

{
"Phrase" : "Four score and seven years ago, our fore-fathers brought forth upon this continent, a new nation conceived in liberty...",
"Version" : "Abraham Lincoln"
}

现在,当您将一个观察者附加到该JSON时,您将获得上述结构的快照。然后在回调中循环snapshot.children,这意味着item变量是上面单个PhraseVersion变量的快照,这些都是简单的String值,而不是字典。

因此,这里不需要snapshot.children上的循环,因为您正在观察一个单独的D176节点。因此:

myRef.observe(.value, with: {
snapshot in
var newItems: [FavItem] = []
let mItem = FavItem(snapshot: snapshot)
newItems.append(mItem)

相关内容

最新更新