How can i stop firebase getting data from local caching - ios

There was a null user in my firebase table and some of devices fetched that and crashing since. I deleted that user. Is there any way i can fix this without updating the build.
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)
Thanks in Advance!

Related

Firebase returning Unknown data from child

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!

How to parse a firebase real time database

How I can parse firebase realtime database?
So far my code is:
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("data").observe(.childAdded) { (snapshot) in
print("snapshot = \(snapshot)")
}
I can not enter the condition.
print("url = \(ref.url)")
url = "https://gdenamaz.firebaseio.com"
this variant don't work too
var ref: DatabaseReference!
ref = Database.database().reference().child("data")
ref.observeSingleEvent(of: .value) { (snapshot) in
for data in snapshot.children {
print("data = \(data)")
}
}
To reference the official docs -
refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
// ...
})
You want to be looking for the snapshot.value not snapshot.children
A further example
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
also, .childAdded will only trigger when a child is added. IE, nothing will happen until you actually change something in that node reference.

Swift retrieve data from Firebase

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)
}

Retrieving and Reading Data as NSArray from Firebase (Swift 3)

I'm working through a course on Udemy to build a chat app with Firebase, Backendless, and Swift. All of the issues (it was written for Swift 2 not 3) I've been able to resolve myself, but this one has me stumped. This function is supposed to retrieve data from the Firebase database, and apparently it was supposed to retrieve it as an NSArray, but it now retrieves it as an NSDictionary, which is making a huge list of errors in the other functions because it's not expecting a dictionary.
func loadRecents() {
firebase.childByAppendingPath("Recent").queryOrderedByChild("userId").queryEqualToValue(currentUser.objectId).observeEventType(.Value, withBlock: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let sorted = (snapshot.value.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptior(key: "date", ascending: false)])
}
})
}
I've updated to Swift 3 as far as:
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! NSDictionary
}
})
}
Of course, using as! NSArray does not work. Would very much appreciate it if anyone can suggest a method to update this to use Swift 3, sort it by a value in the data, and be able to access it later on. Thanks!
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! [String:AnyObject]
}
})}
or you can use also let values = snapshot.value as! [Any]
Hope this will help you, try this code:
func loadRecents() {
let ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
guard let mySnapshot = snapshot.children.allObjects as? [FIRDataSnapshot] else { return }
for snap in mySnapshot {
if let userDictionary = snap.value as? [String: Any] {
print("This is userKey \(snap.key)")
print("This is userDictionary \(userDictionary)")
}
}
})
}

querying messages in firebase using swift [duplicate]

I have a Firebase resource that contains several objects and I would like to iterate over them using Swift.
What I expected to work is the following (according to the Firebase documentation)
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)
}
})
So it seems there is a problem with Swift iterating over the NSEnumerator object returned by Firebase.
Help is really welcome.
If I read the documentation right, this is what you want:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
print(rest.value)
}
}
A better way might be:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { 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)
}
}
The first method requires the NSEnumerator to return an array of all of the objects which can then be enumerated in the usual way. The second method gets the objects one at a time from the NSEnumerator and is likely more efficient.
In either case, the objects being enumerated are FIRDataSnapshot objects, so you need the casts so that you can access the value property.
Using for-in loop:
Since writing the original answer back in Swift 1.2 days, the language has evolved. It is now possible to use a for in loop which works directly with enumerators along with case let to assign the type:
var ref = Firebase(url: MY_FIREBASE_URL)
ref.observeSingleEvent(of: .value) { snapshot in
print(snapshot.childrenCount) // I got the expected number of items
for case let rest as FIRDataSnapshot in snapshot.children {
print(rest.value)
}
}
I have just converted the above answer to 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)
}
})
A better way might be:
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)
}
})
This is pretty readable and works fine:
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! String
}
})
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? [String: Any] else { continue }
let username = restDict["username"] as? String
}
})
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! [String: Any])["xxx"]
})
print(results)
}
}
Firebase 7.3.0
Database.database().reference().child("key").observe(.value) { snapshot in
if let datas = snapshot.children.allObjects as? [DataSnapshot] {
let results = datas.compactMap({
($0.value)
})
print(results)
}
}
If you have multiple keys/values, and want to return an array with dictionary elements, declare an array:
var yourArray = [[String: Any]]()
then change block body to this:
let children = snapshot.children
while let rest = children.nextObject() as? DataSnapshot, let value = rest.value {
self.yourArray.append(value as! [String: Any])
}

Resources