在Swift中重复使用快照子项(Firebase)
我有一个Firebase资源,其中包含几个对象,我想使用Swift迭代它们。 我期望的工作如下(根据Firebase文档)
https://www.firebase.com/docs/ios-api/Classes/FDataSnapshot.html#//api/name/children
var ref = Firebase(url:MY_FIREBASE_URL) ref.observeSingleEventOfType(.Value, withBlock: { snapshot in println(snapshot.childrenCount) // I got the expected number of items for rest in snapshot.children { //ERROR: "NSEnumerator" does not have a member named "Generator" println(rest.value) } })
所以看起来Swift在遍历Firebase返回的NSEnumerator对象时存在一个问题。
帮助真的很受欢迎。
如果我正确阅读文档 ,这是你想要的:
var ref = Firebase(url:MY_FIREBASE_URL) ref.observeSingleEventOfType(.Value, withBlock: { snapshot in println(snapshot.childrenCount) // I got the expected number of items for rest in snapshot.children.allObjects as [FIRDataSnapshot] { println(rest.value) } })
更好的方法可能是:
var ref = Firebase(url:MY_FIREBASE_URL) ref.observeSingleEventOfType(.Value, withBlock: { snapshot in println(snapshot.childrenCount) // I got the expected number of items let enumerator = snapshot.children while let rest = enumerator.nextObject() as? FIRDataSnapshot { println(rest.value) } })
第一种方法需要NSEnumerator
返回所有对象的数组,然后按照通常的方式枚举。 第二种方法从NSEnumerator
一次获取一个对象,可能更有效。
无论哪种情况,枚举的对象都是FIRDataSnapshot
对象,所以您需要强制转换以便可以访问value
属性。
这是非常可读的,工作正常:
var ref = Firebase(url:MY_FIREBASE_URL) ref.childByAppendingPath("some-child").observeSingleEventOfType( FEventType.Value, withBlock: { (snapshot) -> Void in for child in snapshot.children { let childSnapshot = snapshot.childSnapshotForPath(child.key) let someValue = childSnapshot.value["key"] as! String } })
我刚把上面的答案转换成Swift 3:
ref = FIRDatabase.database().reference() ref.observeSingleEvent(of: .value, with: { snapshot in print(snapshot.childrenCount) // I got the expected number of items for rest in snapshot.children.allObjects as! [FIRDataSnapshot] { print(rest.value) } })
更好的方法可能是:
ref = FIRDatabase.database().reference() ref.observeSingleEvent(of: .value, with: { snapshot in print(snapshot.childrenCount) // I got the expected number of items let enumerator = snapshot.children while let rest = enumerator.nextObject() as? FIRDataSnapshot { print(rest.value) } })
ref = FIRDatabase.database().reference().child("exampleUsernames") ref.observeSingleEvent(of: .value, with: { snapshot in for rest in snapshot.children.allObjects as! [FIRDataSnapshot] { guard let restDict = rest.value as? [String: Any] else { continue } let username = restDict["username"] as? String } })
Firebase 4.0.1
Database.database().reference().child("key").observe(.value) { snapshot in if let datas = snapshot.children.allObjects as? [DataSnapshot] { let results = datas.flatMap({ ($0.value as! [String: Any])["xxx"] } print(results) } }
如果您有多个键/值,并且想要使用dictionary
元素return
一个array
,则声明一个数组:
var yourArray = [[String: Any]]()
然后将块体更改为:
let children = snapshot.children while let rest = children.nextObject() as? DataSnapshot, let value = rest.value { self.yourArray.append(value as! [String: Any]) }