J'ai une ressource Firebase qui contient plusieurs objects et je voudrais parcourir sur eux en utilisant Swift. Ce que je m'attendais à travailler est le suivant (selon la documentation de 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) } })
Il semble donc qu'il y ait un problème avec Swift itérant sur l'object NSEnumerator returnné par Firebase.
L'aide est vraiment la bienvenue.
Si je lis bien la documentation, voici ce que vous voulez:
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) } })
Une meilleure façon pourrait être:
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) } })
La première méthode nécessite que NSEnumerator
returnne un tableau de tous les objects qui peuvent ensuite être énumérés de la manière habituelle. La deuxième méthode récupère les objects un à la fois à partir du NSEnumerator
et est probablement plus efficace.
Dans les deux cas, les objects énumérés sont des objects FIRDataSnapshot
, vous avez donc besoin des conversions pour pouvoir accéder à la propriété value
.
C'est assez lisible et fonctionne bien:
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! Ssortingng } })
Je viens de convertir la réponse ci-dessus à 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) } })
Une meilleure façon pourrait être:
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? [Ssortingng: Any] else { continue } let username = restDict["username"] as? Ssortingng } })
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! [Ssortingng: Any])["xxx"] } print(results) } }
Si vous avez plusieurs keys / valeurs et que vous voulez return
un array
avec des éléments de dictionary
, déclarez un tableau:
var yourArray = [[Ssortingng: Any]]()
puis changez le corps du bloc en ceci:
let children = snapshot.children while let rest = children.nextObject() as? DataSnapshot, let value = rest.value { self.yourArray.append(value as! [Ssortingng: Any]) }