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 .
})
Related
I am trying to get data from firebase table but it is giving me a user which is not present in firebase database.
let ref = Database.database().reference().child("users")
ref.observe(.value, with: { (snapShot: DataSnapshot!) in
let totalUsers = snapShot.childrenCount
self.usersRefHandle = ref.observe(.childAdded , with: { (snapshot) -> Void in
let userDict = snapshot.value as! [String: Any]
print(snapshot.key)
it is printing all keys in alphabetical order but suddenly i am getting a key which is not present in my users table.Help me here please.
Thank You!
I have tried many solutions to make this work, but it doesn't seem to work with me. These are the solutions I have tried:
Firebase Retrieving Data in Swift
https://firebase.google.com/docs/database/ios/read-and-write
https://www.raywenderlich.com/187417/firebase-tutorial-getting-started-3
I am trying to retrieve the deviceToken of the currently logged in user, for example if John logs in, it would assign or retrieve his deviceToken and assign it to a variable.
The closest I have got was with this code, but I get every profile with every data stored in that profile instead of the currently logged in one.
let userID = Auth.auth().currentUser?.uid
let ref = Database.database().reference(withPath: "users/profile/\(userID)")
ref.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
return
}
let token = snapshot.childSnapshot(forPath: "deviceToken").value
print(token!)
})
There is an example on the documentation, modifying for your case:
let userID = Auth.auth().currentUser?.uid
ref.child("users").child("profile").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let deviceToken = value?["deviceToken"] as? Int ?? ""
// ...
}) { (error) in
print(error.localizedDescription)
}
I've have tried different attempts of retrieving data from firebase (Database), but sadly with no luck :I... So I was wondering If this is the correct way of doing it?
let dBRef = Database.database().reference()
dBRef.child("Users").child("Advertisements").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
let imageAd = snapshotValue?["imageAd"] as? String
let priceAd = snapshotValue?["priceAd"] as? String
Im not sure if I actually receive the data, and Im not sure of how to test this as well... I have tried debugging but with no luck...
So my question is, is my code wrongly done? and if not how do I check If I actually receive the data??
You are observing the childAdded event.
So your closure will only be executed when a new value I inserted into Users/Advertisements.
Try this code instead
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
}
let imageAd = dict["imageAd"] as? String
let priceAd = dict["priceAd"] as? String
})
The closure will be executed only once and "almost" immediately.
to test if your data was pulled in accurately, you can add, below your code: print(imageAd). assuming this code is in viewDidLoad then it will show up in the console when the view controller comes up.
also, I believe .queryOrderedByKey(...) is now .queryOrdered(byKey:...)
keep in mind that .observe() essentially opens a connection to your firebase. if you want a live, realtime connection to stay open and listen for updates to data, this makes sense. if you only need the data once, when you load something, consider using .observeSingleEventOf() instead. if you are going to use .observe() , you should also use .removeAllObservers() to close the connection when you need it to be closed.
it seems like you are just trying to add this info which you've previously set up in your DB. I would do it like this - (keep in mind you were missing the uid step in your json. I have assumed it is the current user in the code below, but if it's a static user, you'd need to define it as a string):
let uid = Auth.auth().currentUser?.uid
dBRef.child(Users).child(uid).child(Advertisements).observeSingleEvent(of:
.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let imageAd = value?["imageAd"] as? String ?? ""
let priceAd = value?["priceAd"] as? String ?? ""
print("imageAd: \(imageAd!)")
print("priceAd: \priceAd!)")`
})
I can see one problem is that your path is wrong. Try something like:
let dBRef = Database.database().reference()
dBRef.child("Users/\(FirAuth.auth.currentUser.uid)/advertisements")
dbRef.queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
I was having the same problem as yours but by looking at the firebase Doc you can see how to retrieve data easily.
lazy var databaseRef = Database.database().reference().child(yourpath).("Advertisements")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
if let email = postDict["Email"] {
print(email)
}
}) { (error) in
print(error.localizedDescription)
}
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)
}
}
})
}
}
})
I'm trying to retrieve specific data from just the currently logged in user. My data in my database looks like this:
For example, I want to just grab the full_name and save it in a variable userName. Below is what I'm using to grab my data
ref.queryOrderedByChild("full_name").queryEqualToValue("userIdentifier").observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
print(snapshot.value)
// let userName = snapshot.value["full_name"] as! String
})
Unfortunately, this is what my console prints.
I would appreciate any help :) Thank you!
It gives you that warning message indexOn because you are doing a query.
you should define the keys you will be indexing on via the .indexOn
rule in your Security and Firebase Rules. While you are allowed to
create these queries ad-hoc on the client, you will see greatly
improved performance when using .indexOn
As you know the name you are looking for you can directly go to that node, without a query.
let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("stephenwarren001#yahoo.com")
// only need to fetch once so use single event
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
if !snapshot.exists() { return }
//print(snapshot)
if let userName = snapshot.value["full_name"] as? String {
print(userName)
}
if let email = snapshot.value["email"] as? String {
print(email)
}
// can also use
// snapshot.childSnapshotForPath("full_name").value as! String
})
Swift 4
let ref = Database.database().reference(withPath: "user")
ref.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() { return }
print(snapshot) // Its print all values including Snap (User)
print(snapshot.value!)
let username = snapshot.childSnapshot(forPath: "full_name").value
print(username!)
})
{
"rules": {
"tbl_name": {
".indexOn": ["field_name1", "field_name2"]
},
".read": true,
".write": true
}
}
You can apply indexOn on any field. Add this json in rules security and rules tab.
Hope this works for you. :)
It retrieves logged in user data:
let ref = FIRDatabase.database().reference(fromURL: "DATABASE_URl")
let userID = FIRAuth.auth()?.currentUser?.uid
let usersRef = ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
let ref = Database.database().reference().child("users/stephenwarren001#yahoo.com")
ref.observeSingleEvent(of: .value, with: { (snap : DataSnapshot) in
print("\(String(describing: snap.value))")
}) { (err: Error) in
print("\(err.localizedDescription)")
}
var refDatabase = DatabaseReference()
refDatabase = Database.database().reference().child("users");
let refUserIdChild = refDatabase.child("stephenwarren001#yahoo.com")
refUserIdChild.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() { return }
print(snapshot) // Its print all values including Snap (User)
print(snapshot.value!)
if let tempDic : Dictionary = snapshot.value as? Dictionary<String,Any>
{
if let userName = tempDic["full_name"] as? String {
self.tfName.text = userName
}
if let email = tempDic["email"] as? String {
self.tfEmail.text = email
}
}
})