【发布时间】:2017-04-15 05:17:12
【问题描述】:
在 Firebase 中侦听新对象时,我收到此错误:无法将 NSTaggedPointerString 类型的值转换为 NSDictionary。这是监听已注册用户的代码。
FIRAuth.auth()!.addStateDidChangeListener { auth, user in
guard let user = user else { return }
self.user = User(authData: user)
let userref = FIRDatabase.database().reference(withPath: "users").child(self.user.uid)
userref.observe(.value, with: { snapshot in
print(snapshot.value!)
var newItems: [UserItem] = []
for item in snapshot.children {
let userDetail = UserItem(snapshot: item as! FIRDataSnapshot) /////////// CRASHES HERE //////////
newItems.append(userDetail)
}
self.userItem = newItems
})
print(self.user.uid)
}
当错误出现时,它指向这里:
init(snapshot: FIRDataSnapshot) {
key = snapshot.key
let snapshotValue = snapshot.value as! [String:Any] ///// ERROR HERE
name = snapshotValue["name"] as! String
email = snapshotValue["email"] as! String
age = snapshotValue["age"] as! String
ref = snapshot.ref
}
控制台正在正确打印 Firebase 内部的内容,并且数据在那里并且存在,但是这种转换或数据读取错误不断发生。它与转换有关,但我不确定。
【问题讨论】:
-
错误信息说
snapshot.value不是Dictionary,而是String。 -
所以我应该写,让snapshotValue = snapshot.value as! [字典:任何]?
-
因为我试过这个,让 snapshotValue = (snapshot.value as Disctionary) as! [String:Any] 但这不起作用
-
as! [Dictionary:Any]?仍然更糟,更糟。 -
也试过这个,if let dictionary = snapshot.value as? NSDictionary { if let username = dictionary["name"] as?字符串 { 打印(用户名)}
标签: ios swift firebase firebase-realtime-database