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."
Related
JSON
switch
uid
switch : true
uid2
switch : false
What I tried that doesn't work
#objc func didLongPress() {
let databaseRef = Database.database().reference().child("switch").child(self.postID)
databaseRef.queryOrdered(byChild: "switch").queryEqual(toValue: "true").observeSingleEvent(of: .value) { (snapshot) in
print(snapshot)
if snapshot.exists() {
print("Address is in DB")
} else {
print("Address doesn't exist")
}
}}
//////note it picks up self.postID successfully so error is after that. print snapshot gives null
also tried
let databaseRef = Database.database().reference().child("switch").child(self.postID).child("switch/\true")
databaseRef.observeSingleEvent(of: .value) { (snapshot) in
print(snapshot)
if snapshot.exists() {
print("Address is in DB")
} else {
print("Address doesn't exist")
}
}
}
So in theory this should be a really easy, elementary task. The first of the above mentioned attempts should work. There are no permission errors, but console simply produce null as the snapshot print. That is so weird.
If I test a simple snapshot to see what prints with .child(switch).child(self.postID).child(switch) - it prints either 1 for true and 0 for false. So that works.
EDIT: I think this is because it is in an objective c function. I just realized that. I need it in objective C, because if gets called on long press, which uses objective c function
Try:
(Change database child path as per your need.)
Database.database().reference().child("switch").child(self.postID).queryOrdered(byChild: "switch").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject] {
print("Address is in DB")
} else {
print("Address doesn't exist")
}
}) { (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 am creating an app similar to Instagram. I created a logged in user feed tab with this code
FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
let key = snapshot.key
let snapshot = snapshot.value as? NSDictionary
snapshot?.setValue(key, forKey: "uid")
print(snapshot)
if(key == self.loggedUser?.uid)
{
print("same as logged in user")
}
else
{
self.usersArray.append(snapshot)
self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
}
}) { (error) in
print(error.localizedDescription)
}
However, I want to create a tab that outputs all the users in the database posts, but when I use this code
FIRDatabase.database().reference().child("posts").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
It doesn't work.
My Firebase database looks like this
Is there a way I can access the title node of all the users and not only the logged in users.
You can do it like this
FIRDatabase.database().reference().child("posts").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
if let item = child as? FIRDataSnapshot {
// get values
let foo = item["index"] as? String
}
}
}
Here is the firebase data tree
There are two parents and each having two child each. How to retrieve all the data for "sex".
Here's is my code.
ref.child("Doctor").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
for child in result {
print("Here 1")
print(child)
let gender = child.value!["sex"] as? String
print("Here 2")
//print("Sex")
print(gender)
}
} else {
print("no results")
}
}) { (error) in
print(error.localizedDescription)
}
When I am printing the value of gender, it is showing nil value.
You're trying to skip a level in your code. You listen to the value of the root node and then loop over its children. This gets you snapshots of the nodes Msm... and eqn.... If you check inside those nodes, neither of them has a child property sex.
To solve this, add one more loop in your code to get into the push IDs (the keys starting with -K):
ref.child("Doctor").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let result = snapshot.children.allObjects as? [FIRDataSnapshot] {
for child in result {
for child2 in child.children {
let gender = child2.value!["sex"] as? String
print(gender)
}
}
} else {
print("no results")
}
}) { (error) in
print(error.localizedDescription)
}
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
}
}
})