Retrieve Data from an Unknown Child Name with Firebase and Swift

Swift, Firebase retrieving data from unknown child

In your current code you loop over the years already. If you also want to loop over the months, you'll need to add an extra for:

databaseRef = Database.database().reference().child("Users").child(userID!)
databaseRef.observe(.value, with: {(snapshot) in

for year in snapshot.children.allObjects as [DataSnapshot] {
for month in year.children.allObjects as [DataSnapshot] {
print(month.key)
}
}

}){
(error) in
print(error.localizedDescription)
}

This will print the months. You can get properties of the specific month with:

print(month.childSnapshot(forPath:"Key").value)

Retrieve data from an unknown child name with Firebase and Swift

Here's a code snippet that retrieves and prints the uid of each user and their location.

We can further refine our results with a .query

let usersRef = ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { (snapshot) in

for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! [String:AnyObject] //child data
let location = userDict["Location"] as! String
print("key = \(uid) is at location = \(location)")
}
})

how to get data from child node in firebase in iOS

You can go through every child like this:

    // Create a reference to the database path
let ref = Database.database().reference(withPath: "Tasks")

// You can keep your database synced
ref.keepSynced(true)

ref.observe(.value, with: { (snapshot) in

// Checking if the reference has some values
if snapshot.childrenCount > 0 {

// Go through every child
for data in snapshot.children.allObjects as! [DataSnapshot] {
if let data = data.value as? [String: Any] {

// Retrieve the data per child

// Example
let name = data["name"] as? String
let age = data["age"] as? String

// Print the values for each child or do whatever you want
print("Name: \(name)\nAge: \(age)")
}
}
}
})

Get the data from all children in firebase using swift

You'll want to attach the observer one level higher in the JSON, and then loop over the child nodes:

ref.observeSingleEvent(of: .value) { snapshot in
for case let child as FIRDataSnapshot in snapshot.children {
guard let dict = child.value as? [String:Any] else {
print("Error")
return
}
let latitude = dict["Latitude"] as Any
let longtitude = dict["Longtitude"] as Any
print(longtitude)
print(latitude)
}
}

Loop syntax taken from Iterate over snapshot children in Firebase, but also see How do I loop all Firebase children at once in the same loop? and Looping in Firebase

Firebase: Retrieve nested data from unknown children

One way you could do this is by restructuring your database:

"userBroadcasts": {
"ghjghjFc1S3KO0y8yJwORdfgret": { // user ID
"ryrtybgzMiI858YyGua": true, // broadcastID
"jkhjkbgzMiI858YyGua": true, // another broadcastID
// etc..
},
// more users down here...
}

"broadcast": {
"ryrtybgzMiI858YyGua": { // broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false
},
"jkhjkbgzMiI858YyGua": {
"a": "xxx",
"b": "yyy",
"c": true
},
// more broadcasts down here...
}

Then you can get all the broadcasts you want by calling:

FIRDatabase.database().reference().child("broadcast").queryOrdered(byChild: "c").queryEqual(toValue: true)

If you want the userID as well, store this inside the broadcast when you create it, for example:

"broadcast": {
"ryrtybgzMiI858YyGua": { // broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false,
"userID":"ghjghjFc1S3KO0y8yJwORdfgret"
},
"jkhjkbgzMiI858YyGua": {
"a": "xxx",
"b": "yyy",
"c": true,
"userID":"ghjghjFc1S3KO0y8yJwORdfgret"
},
// more broadcasts down here...
}

Embrace denormalisation with the Firebase Database!

How to retrieve data from all the Users using Firebase and Swift

Looks like you misspelled the location key for your dictionary:

let location = userDict["Location"] as! [String: AnyObject]

Replace it with:

let location = userDict["location"] as! [String: AnyObject]

You can always put a breakpoint at the print line and see what your location dictionary looks like with po location in console.

Retrieve data with child from Firebase Database and Populate Object Class using Kotlin

As Sam Stern mentioned in his answer, it's best to create a representation for each class separately. I'll write you the corresponding classes in Kotlin.

This is the User class:

class User (
val firstName: String = "",
val lastName: String = "",
val userLocation: UserLocation? = null
)

And this is the UserLocation class:

class UserLocation (
val lat: Int = 0,
val lng: Int = 0
)

to query this User 1332 and cast it to the User.class object

Please use the following lines of code:

val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val uidRef = rootRef.child("users").child(uid)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val user = dataSnapshot.getValue(User::class.java)
Log.d(TAG, "Lat/Lng: " + user!!.userLocation!!.lat + ", " + user.userLocation!!.lng);
}

override fun onCancelled(databaseError: DatabaseError) {
Log.d(TAG, databaseError.message) //Don't ignore errors!
}
}
uidRef.addListenerForSingleValueEvent(valueEventListener)

In which the uid should hold a value like 131232. The output in your logcat will be:

Lat/Lng: 15.2512312, -12.1512321

In the same way you can get: user!!.firstName and user!!.lastName.



Related Topics



Leave a reply



Submit