Swift Firebase read children of a child - swift

So I am trying to read the children of the autoID children beneath "Recipes" below is a picture of my Firebase database and beneath that is the method that is supposed to retrieve the value of "Description" and "Name" and insert them into variables.
The error that I am currently getting when running the app is this:
Could not cast value of type '__NSCFString' (0x10ad2afb8) to 'NSDictionary' (0x10ad2bfa8).
ref = Database.database().reference()
databaseHandle = ref?.child("Recipes").observe(.childAdded) { (snapshot) in
for snap in snapshot.children
{
let recipeSnap = snap as! DataSnapshot
let recipeID = recipeSnap.key
let dict = recipeSnap.value as! [String:AnyObject]
let recipeName = dict["Name"] as! String
let recipeDescription = dict["Description"] as! String
print("key = \(recipeID) and name = \(recipeName) and description = \(recipeDescription)")
}
}
The print statement is just there for testing.

Try the following and let me know if it works now:
// SEARCHES FOR SHARING CODE IN DATABASE (ONLINE)
let parentRef = Database.database().reference().child("Recipes")
parentRef.observeSingleEvent(of: .value, with: { snapshot in
// SHOWING WHATEVER WAS RECEIVED FROM THE SERVER JUST AS A CONFIRMATION. FEEL FREE TO DELETE THIS LINE.
print(snapshot)
// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
print("– – – Data was not found – – –")
} else {
// DATA WAS FOUND
for user_child in (snapshot.children) {
let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]
// DEFINE VARIABLES FOR LABELS
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
print("– – – Data for the recipe \(recipeName) with the description \(recipeDescription) was found successfully! – – –")
}
}
}
If you only want to retrieve the name and description for one specific recipe, you should change the third line to
parentRef.queryEqual(toValue:DefineWhatToSearchForHere).observeSingleEvent(of: .value, with: { snapshot in
If you constantly want to update to reflect changes, you can either call this function every x seconds using a timer and adding it to override func viewDidLoad() such as
time = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(ViewController.updateFBData), userInfo: nil, repeats: true)
after creating a function called func updateFBData() in which you do whatever you want to do to get new data (see above) and calling it in a defined timeInterval
or you can do what Attila Hegedüs in this excellent tutorial.

Related

Cannot fetch / read data from firebase real-time database to UITableViewController

I am able to successfully write data from my application to my firebase real-time database. I cannot retrieve the data and display it in a UIViewController.
I have search stack, YouTube and firebase docs and no luck. I printed out the count and it returns 0. I believe the For loop isn't iterating or its not appending to my array correctly. I have trie force wrapping and unwrapping refRepairs, and placing databaseHandle in from of it.
override func viewDidLoad() {
super.viewDidLoad()
refRepairs = Database.database().reference().child("repairs");
//observing the data changes
refRepairs!.child("repairs").observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.repairList.removeAll()
//iterating through all the values
for repairs in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let repairObject = repairs.value as? [String: AnyObject]
let brand = repairObject?["brand"]
let id = repairObject?["id"]
let modelNumber = repairObject?["modelNumber"]
//creating artist object with model and fetched values
let repair = RepairModel(id: id as! String?, brand: brand as! String?, modelNumber: modelNumber as! String?)
//appending it to list
print(snapshot.childrenCount)
self.repairList.append(repair)
}
//reloading the tableview
self.doListTableView.reloadData()
}
})
}
I made the changes and it was working!!! Now, I am trying to add records to the database by uid, and I have successfully done it. Now I have the same problem where I can't display the records. I printed the count and it returns 1 record which is correct. Here is the new code.
override func viewDidLoad() {
super.viewDidLoad()
refRepairs = Database.database().reference().child("repairs");
//observing the data changes
//refRepairs!.child("uid").observe(DataEventType.value, with: { (snapshot) in
//observing the data changes
refRepairs!.observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.repairList.removeAll()
//iterating through all the values
for repairs in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let repairObject = repairs.value as? [String: AnyObject]
let brand = repairObject?["brand"]
let uid = repairObject?["uid"]
let id = repairObject?["id"]
let modelNumber = repairObject?["modelNumber"]
//creating artist object with model and fetched values
let repair = RepairModel(uid: uid as! String?, id: id as! String?, brand: brand as! String?, modelNumber: modelNumber as! String?)
//appending it to list
print(snapshot.childrenCount)
self.repairList.append(repair)
}
//reloading the tableview
self.doListTableView.reloadData()
}
})
}
You are looking another second child called repairs when you are "observing the data changes". Try this:
override func viewDidLoad() {
super.viewDidLoad()
refRepairs = Database.database().reference().child("repairs");
//observing the data changes
refRepairs!.observe(DataEventType.value, with: { (snapshot) in
...
If that don't work. Use the observeSingleEvent method from Firebase

Fetch all uid from firebase database using swift code

I have this database (see the link above with the image) and a code with a path, that leads to the destination using:
databaseReference.child("users").child(currentUser!.uid).child("todo-list")
Under the first node "users", the next level is a keyvalue for userID, and later there are more sub-levels "todo-list" etc.
I would like to fetch the data from all uid available. How can I make the query?
Here is the code:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
databaseReference = Database.database().reference()
currentUser = Auth.auth().currentUser
let todoListRef = databaseReference.child("users").child(currentUser!.uid).child("todo-list")
todoListRef.observe(DataEventType.value, with: { (DataSnapshot) in
self.itemsToLoad.removeAll()
let enumerator = DataSnapshot.children
while let todoItem = enumerator.nextObject() as? DataSnapshot
{
let item = todoItem.value as AnyObject
self.itemsToLoad.append(item)
}
self.itemsToLoad = self.itemsToLoad.reversed()
self.tableView.reloadData()
})
}
It's quite similar to the code you already have. Instead of observing /users/$uid, you observe the entire /users node. And then you add an extra loop in the closure, to iterate over all the users.
So:
let usersRef = databaseReference.child("users")
usersRef.observe(DataEventType.value, with: { (usersSnapshot) in
let userEnumerator = usersSnapshot.children
while let user = userEnumerator.nextObject() as? DataSnapshot {
let uid = user.key
let todoEnumerator = user.childSnapshot(forPath: "todo-list").children
while let todoItem = todoEnumerator.nextObject() as? DataSnapshot {
let item = todoItem.value as AnyObject
self.itemsToLoad.append(item)
}
}
})
The added while loops over the users, while the inner while loops over the todo's for each user. I removed the code related to the table view, since what you want to do there doesn't depend on Firebase.

Load data from firebase to a label?

I have data in firebase that I would like to load into a UILabel with Swift.
My data structure looks like:
like-1bf89addclose
artists
-LP6zVO8iekRMMOWe7nm
artistGenre: pop
artistName: postmalone
id: 920930
And my swift code looks like:
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
refHandle = ref.observe(FIRDataEventType.value, with: {(snapshot) in
let dataDict = snapshot.value as! [String: AnyObject]
print(dataDict)
})
ref.child("artists").observeSingleEventOfType(.value, with: {(snapshot) in
let artist = snapshot.value!["artistName"] as! String
let genre = snapshot.value!["artistGenre"] as! String
self.artistlLabel.text = artist
self.genreLabel.text = genre
})
}
where's my mistake? I've tried searching online, but most examples only explain how to put input into tableviews, which has a different code I tried to understand and restructure but couldn't. I know there has to be something wrong with my ref but I can't figure it out.
I'm following a youtube tutorial and this works:
let userID: String = (FIRAuth.auth()?.currentUser?.uid)!
ref.child("Users").child(userID).observeSingleEventOfType(.value, with: {(snapshot) in
let email = snapshot.value!["Email"] as! String
let password = snapshot.value!["Password"] as! String
self.emailLabel.text = email
self.passwordLabel.text = password
})
**issue with this code is I don't need that authentication part (no users have to log in on my app, they're just inputing info in).
You're missing the -LP6zVO8iekRMMOWe7nm level in your reference. Try this:
ref.child("artists/-LP6zVO8iekRMMOWe7nm").observeSingleEventOfType(.value, with: {(snapshot) in
let artist = snapshot.value!["artistName"] as! String
let genre = snapshot.value!["artistGenre"] as! String
print("\(artist) \(genre)")
self.artistlLabel.text = artist
self.genreLabel.text = genre
})
If you want to load all artists, you can load /artists and then loop over the results:
ref.child("artists/-LP6zVO8iekRMMOWe7nm").observeSingleEventOfType(.value, with: {(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let artist = child.value!["artistName"] as! String
let genre = child.value!["artistGenre"] as! String
print("\(artist) \(genre)")
}
})

Getting values from Firebase snapshot in Swift

Im successfully getting data from Firebase but I can't manage to push it into array to use. My database is as follows:
users
-Wc1EtcYzZSMPCtWZ8wRb8RzNXqg2
-email : "mike#gmail.com"
-lists
-LJiezOzfDrqmd-hnoH-
-owner: Wc1EtcYzZSMPCtWZ8wRb8RzNXqg2
-LJif-UgPgbdGSHYgjY6
-owner: Wc1EtcYzZSMPCtWZ8wRb8RzNXqg2
shopping-lists
-LJh6sdBJtBCM7DwxPRy
-name: "weekly shopping"
-owner: "mike#gmail.com"
I have a home page after login that shows existing shopping lists on table if they exist. On viewDidLoad() I get shopping list IDs from the user and use those IDs as a reference to get details from shopping-lists.
However, I cant manage to save these data into an array as it gets deleted after closure. How can I do that in a clean way?
override func viewDidLoad() {
super.viewDidLoad()
SVProgressHUD.show()
tableView.allowsMultipleSelectionDuringEditing = false
// Sets user variable - must have
Auth.auth().addStateDidChangeListener { auth, user in
guard let user = user else { return }
self.user = User(authData: user)
// If new user, write into Firebase
self.usersRef.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.hasChild(self.user.uid) {
self.usersRef.child(user.uid).setValue(["email": user.email!])
}
})
// Get shopping lists data from "users/lists"
self.usersRef.child(user.uid).child("lists").observe(.value, with: { snapshot in
// Get list IDs
if snapshot.exists() {
if let result = snapshot.children.allObjects as? [DataSnapshot] {
for child in result {
self.listNames.append(child.key)
}
}
}
// Use list IDs - to get details
for item in self.listNames {
let itemRef = self.shoppingListsRef.child(item)
itemRef.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let value = snapshot.value as? [String: Any] {
let name = value["name"] as? String ?? ""
let owner = value["owner"] as? String ?? ""
let shoppingList = ShoppingList(name: name, owner: owner)
self.items.append(shoppingList)
}
})
}
})
self.tableView.reloadData()
SVProgressHUD.dismiss()
}
}
(the question is a bit unclear so several parts to this answer to cover all possibilities. This is Swift 4, Firebase 4/5)
You don't really need to query here since you know which nodes you want by their key and they will always be read in the in order of your listNames array. This assumes self.listNames are the keys you want to read in.
for item in listNames {
let itemRef = shoppingListsRef.child(item)
itemRef.observe(.value, with: { (snapshot) in
if let value = snapshot.value as? [String: Any] {
let name = value["name"] as? String ?? ""
let owner = value["owner"] as? String ?? ""
print(name, owner)
}
})
}
Generally, queries are used when you are searching for something within a node - for example if you were looking for the node that contained a child name of 'weekly shopping'. Other than that, stick with just reading the nodes directly as it's faster and has less overhead. Keep reading...
I also removed the older NSDictionary and went with the Swift [String: Any] and modified your error checking
However, the real issue is reading that node with an .observe by .value. Remember that .value reads in all children of the node and then the children need to be iterated over to get each separate DataSnapshot. Also, .observe leaves an observer on the node notifying the app of changes, which I don't think you want. So this will answer the question as posted, (and needs better error checking)
for item in listNames {
let queryRef = shoppingListsRef
.queryOrdered(byChild: "name")
.queryEqual(toValue: item)
queryRef.observe(.value, with: { (snapshot) in
for child in snapshot.children { //even though there is only 1 child
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let name = dict["name"] as? String ?? ""
let owner = dict["owner"] as? String ?? ""
print(name, owner)
}
})
}
And the answer...
This is probably more what you want...
for item in listNames {
let queryRef = shoppingListsRef
.queryOrdered(byChild: "name")
.queryEqual(toValue: item)
queryRef.observeSingleEvent(of: .childAdded, with: { snapshot in
let dict = snapshot.value as! [String: Any]
let name = dict["name"] as? String ?? ""
let owner = dict["owner"] as? String ?? ""
print(name, owner)
})
}
note the .childAdded instead of .value which presents the snapshot as a single DataSnapshot and doesn't need to be iterated over and the .observeSingleEvent which does not leave an observer attached to each node.
Edit
Based on additonal information, it would be best too change the structure to this
shopping-lists
-LJh6sdBJtBCM7DwxPRy
-name: "weekly shopping"
-uid: "Wc1EtcYzZSMPCtWZ8wRb8RzNXqg2"
and then when the user logs in just query the shopping lists node for any uid that's theirs.

Firebase Add New Key/Value to Pre-existing database without crashing xcode

` let query = ref?.child("Reviews").queryOrdered(byChild: "UserID").queryEqual(toValue: myUser.userId)
query?.observeSingleEvent(of: .value) { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let uid = dict["UserID"] as! String
let review = dict["Body"] as! String
let rating = dict["Rating"] as! String
let titleID = dict["TitleID"] as! String
let reviewID = dict["ReviewID"] as! String
let ratingID = dict["RatingID"] as! String
`
THE ERROR OCCURS AT THE ratingID call to the database. It unwraps nil.
I am trying to adapt a pre existing Firebase database with a new key/value.
I then try to display entries in my tableview and I get a crash with unwrap returning nil. I know why this is happening and it's because the previous data does not have the new key/value I want to include in the node going forward. I have tried many different things such as if let and guard let without much fortune. How do I add new key/Values and still have the tableview read entries that don't have the new value?
I include an image of the current node and I want to add a 'RatingsID' to the node. When I do, I get the unwrap nil error.
Database node prior to new key/value
Your code is super close, just need to protect the code in case the ratingID key doesn't exist.
So change
let ratingID = dict["RatingID"] as! String
to
let ratingID = dict["RatingID"] as! String ?? ""
So if the RatingID node does not exist, you'll set ratingID to an empty string (or whatever string you want)
You could also code it to only operate on the value of that key if the node exists (not nil)
if let someVal = dict["xxx"] {
//do something with someVal
} else {
print("xxx node wasn't found")
}
Here's a complete example: We are reading some messages from the messages node and some of them have a test_key node and some dont. For those that don't, default string is assigned to test
let postsRef = self.ref.child("messages")
postsRef.observe(.childAdded) { snapshot in
let dict = snapshot.value as! [String: Any]
let msg = dict["msg"] as! String
let test = dict["test_key"] ?? "default string"
print(msg, test)
}