Iterate through all keys of one child in Firebase - ios

This is my structure in the Firebase Realtime database:
I want to get for all products the name.
Here's what I tried:
database.child("customerID").child("productTopSeller").observe(FIRDataEventType.value, with: { (snapshot) in
for childSnap in snapshot.children.allObjects {
let product = childSnap as! FIRDataSnapshot
print(product.value?["name"] as? String ?? "")
}
}) { (error) in
print(error.localizedDescription)
}
But this gives my following error:
Type 'Any' has no subscript members.
I know I would need to cast the snapshot somehow but couldn't figure out how to do this. using Swift 3.

You need to cast product.value to [String:Any]. Look ad the following code
ref.child("customerID").child("productTopSeller").observeSingleEvent(of: .value, with: { snapshot in
let names = snapshot
.children
.flatMap { $0 as? FIRDataSnapshot }
.flatMap { $0.value as? [String:Any] }
.flatMap { $0["name"] as? String }
print(names)
})
Please note I am using observeSingleEvent in order to get only one callback from Firebase.
Your code does use observe instead which produce a callback every time the observed data does change.

Related

how to delete child record from firebase in swift?

I wanted to delete this record in firebase, where i don't have the name of the key. so, I don't know how to do it. can anybody help me with this?
The code for getting array is as follows
var databaseRefer : DatabaseReference!
let userID = Auth.auth().currentUser?.uid
databaseRefer = Database.database().reference(withPath: userID!)
databaseRefer.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() { return }
if snapshot.value is NSNull {
print("not found")
} else {
for child in snapshot.children {
let snap = child as! DataSnapshot
print(dict)
dict.forEach { item in
print(item.value)
}
}
}
})
https://firebase.google.com/docs/database/ios/read-and-write
"The simplest way to delete data is to call removeValue on a reference to the location of that data."

How to get values inside nested keys in Firebase on Swift

I'm trying to get values inside two nested keys in Firebase.
:
I need to put all the value of name inside an array. Here is my code where I'm accessing just the node "user". I was thinking that I could use "queryOrderedByKey" one after another, but in that case xCode crashes and says something like multiple quires aren't allowed.
Database.database().reference().child("user").queryOrderedByKey().observe(.childAdded) { (snapshot) in
if snapshot.value != nil {
let result = snapshot.value as! [String : AnyObject]
if let name = result["name"] as? String {
self.myArray.append(name)
}
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}
And this is what I'm getting when printing the result.
Here is the answer
Database.database().reference().child("user").observe(.childAdded) { (snapshot) in
if let dictinoary = snapshot.value as? [String: Any] {
if let myFinalStep = dictinoary["GeneralInformation"] as? [String: Any] {
print(myFinalStep["name"])
}
}
}
Tigran's answer is very good but here's an alternative. This code iterates over each child node within 'user' node and looks into a deep path to get the name. Note this leaves a childAdded observer to the user node so if any additional nodes are added, this will fire again.
let usersRef = self.ref.child("user")
usersRef.observe(.childAdded, with: { snapshot in
if let name = snapshot.childSnapshot(forPath: "GeneralInformation")
.childSnapshot(forPath: "name").value as? String {
print(name)
}
})
If you want to read the names in once and not leave an observer, here's an alternative
let usersRef = self.ref.child("user")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
if let name = snap.childSnapshot(forPath: "GeneralInformation")
.childSnapshot(forPath: "name").value as? String {
print(name)
}
}
})
I was feeling Swifty so here's a third variant if you don't want to leave an observer. Note that if the node containing the name does not exist, the resulting array will contain "No Name" at that index.
let usersRef = self.ref.child("uses")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
let myUsers = snapshot.children.allObjects.map { $0 as! DataSnapshot }
let names = myUsers.map { $0.childSnapshot(forPath: "GeneralInformation")
.childSnapshot(forPath: "name")
.value as? String ?? "No Name" }
print(names)
})

Swift, iOS: How do I extract data from my firebase database?

This is my firebase database.
I wish to go through my database to grab each ticket's value such as "ignore", "Peter rabbit....", "Incredibles 2....", etc.
Currently I am extracting data like this:
ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
ref?.child("users").child(uid!).observe(.childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:String] {
self.movieNameFromTickets.append(myValue)
}
})
But I feel that it isn't a good way to extract data because if I have another structure like tickets, it might print out the wrong information.
What would be a better way to extract my tickets' values?
Thanks :)
Try this :
Database
.database()
.reference()
.child("Users")
.child(Auth.auth().currentUser!.uid)
.child("Advertisements")
.queryOrderedByKey()
.observeSingleEvent(of: .value, with: { snapshot in
guard let dict = snapshot.value as? [String:Any] else {
print("Error")
return
}
// get value from dict here .
})

Firebase snapshot returns null

Hi guys I have been using firebase to write and read values from the database. It was working awesome until I wrote a function to retrieve values or products stored using swift in the following way.
Here is my code
func retrieveLiveUrlFor(product: Product){
if let path = product.prodRef{
print("Looking for : \(path)")
var liveUrl = ""
let ref = Database.database().reference(withPath: path)
ref.observe(. value, with: {
snapshot in
print("Snap : \(snapshot.value)")
if snapshot.exists(){
print("Snap : \(snapshot.value)")
let dic = snapshot.value as? NSDictionary
if dic != nil{
let url = dic?["liveUrl"] as? String
print("Url is here")
if url != nil{
print("URL is not nil")
liveUrl = url as! String
}
}
}
if (self.productdelegate != nil){
print("Calling Product delegate")
self.productdelegate?.liveUrlObtained!(liveUrl: liveUrl)
}
})
}
}
And this is the value of the path that I am trying to retrieve
Products/Live/Global/WpMvDJZUclRlfHFJsSlBEbi0jHf1
And here is the snap of the firebase database
The snapshot.value alwasy returns null in swift.
When I print using
print("Snap: \(snapshot.value)")
It prints the following
Snap : Optional()
Please guide me what I am doing wrong so that I can get to it.
If you are observing using the .value event, then a return of snapshot.value as nil means that the snapshot value does not exist at that reference. Try printing the snapshot as a whole and the snapshot.key
ideally the reference you need is
let ref = Database.database.reference().child("Products").child("Live").child("Global").child("WpMvDJZUclRlfHFJsSlBEbi0jHf1")
The observer would function like this:
ref.observe(.value) {(snapshot) in
print(snapshot.value!)
}

Firebase retrieve data below auto ID In Swift

I'm in trouble in retrieving data from Firebase.
I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView.
Here is my JSON tree (used childByAutoId())
And Here is my Swift Code
dbRef = Database.database().reference()
dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in
for snap in snapshot.children {
let userSnap = snap as! DataSnapshot
let contactName = userSnap.value as? String
self.pickOption.append("\(contactName)")
}
})
But the result shows me all nil data... looks like this.
How Can I fix it..?
I solved myself!
But first of all, I decided not to use UIPickerView.
And what I wanna do is to add data below auto ID.
I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :)
dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
let orderID = child.key as String //get autoID
self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in
if let nameDB = snapshot.value as? String {
if self.debtorName == nameDB {
self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data)
}
}
})
}
}
})

Resources