从Firebase检索并读取数据作为NSArray(Swift 3)
问题描述:
我正在通过Udemy上的一门课程构建与Firebase,Backendless和Swift的聊天应用程序。所有的问题(它是为Swift 2而不是3写的)我已经能够解决我自己,但是这一个让我难住。这个函数应该从Firebase数据库中检索数据,显然它应该将它作为一个NSArray检索出来,但是现在它将它作为一个NSDictionary进行检索,它在其他函数中制作了大量的错误列表,因为它并不期待字典。从Firebase检索并读取数据作为NSArray(Swift 3)
func loadRecents() {
firebase.childByAppendingPath("Recent").queryOrderedByChild("userId").queryEqualToValue(currentUser.objectId).observeEventType(.Value, withBlock: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let sorted = (snapshot.value.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptior(key: "date", ascending: false)])
}
})
}
我尽量更新,斯威夫特3为:
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! NSDictionary
}
})
}
当然,使用as! NSArray
不起作用。如果有人能提出一个方法来更新它来使用Swift 3,按照数据中的值对它进行排序,并且能够稍后访问它,我们将非常感激。谢谢!
答
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! [String:AnyObject]
}
})}
,或者您可以使用也let values = snapshot.value as! [Any]
答
希望这会帮助你,试试这个代码:
func loadRecents() {
let ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
guard let mySnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] else { return }
for snap in mySnapshot {
if let userDictionary = snap.value as? [String: Any] {
print("This is userKey \(snap.key)")
print("This is userDictionary \(userDictionary)")
}
}
})
}
谢谢,这个帮助,但我从做更多的研究看,我应该在snapshot.children中使用'for child'让myvalue = child.value [“my value”] as!字符串 }'或类似的东西来梳理子节点。但是,当我这样做时它说“NSFastEnumerationIterator没有元素值”,那么它建议我把它投到AnyObject,但当然这也不起作用。你知道如何做这个工作吗? –
@EthanT首先你必须检查“子”返回类型做调试模式 – ItsMeMihir