Swift retrieve data from Firebase - ios

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

Related

Retrieving data from currently logged in user Firebase

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

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

Firebase Accessing Snapshot Value Error in Swift 3

I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.
My code:
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value!["fullName"] as! String
let homeAddress = snapshot.value!["homeAddress"] as! [Double]
let email = snapshot.value!["email"] as! String
}
The error is around the three variables stated above and states:
Type 'Any' has no subscript members
Any help would be much appreciated
I think that you probably need to cast your snapshot.value as a NSDictionary.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["fullName"] as? String ?? ""
let homeAddress = value?["homeAddress"] as? [Double] ?? []
let email = value?["email"] as? String ?? ""
}
You can take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write
When Firebase returns data, snapshot.value is of type Any? so as you as the developer can choose to cast it to whatever data type you desire. This means that snapshot.value can be anything from a simple Int to even function types.
Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
{
let username = firebaseDic["fullName"] as! String
let homeAddress = firebaseDic["homeAddress"] as! [Double]
let email = firebaseDic["email"] as! String
}
else
{
print("Error retrieving FrB data") // snapshot value is nil
}
}

Resources