Issues when trying to remove the firebase reference - swift

I am having some issues while trying to delete one of the tableView row - in my case I was trying to delete the data from Firebase and then reload the table view.
See the function below:
func deleteMeds() {
Database.database().reference().child("Meds_Database").child("UsersID").child((Auth.auth().currentUser?.uid)!).child("User_Medications").observe(DataEventType.childRemoved, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let medication = Meds()
medication.medName = (dictionary["Medication_Name"]) as! String
medication.medDosage = (dictionary["Medication_Dosage"]) as! String
medication.medEdit = (dictionary["Medication_Frequency"]) as! String
medication.medAlarm = (dictionary["Medication_Reminder"]) as! String
self.meds.remove(at: 0)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
print(snapshot)
}, withCancel: nil)
}
I think I am getting confused with the Firebase Syntax... Can somebody help me? The database is like this:
I am sure someone can help

You only need to delete the relavant object not always index 0 here
self.meds.remove(at: 0)
So replace it with
self.meds = self.meds.filter{ $0 != medication }
and adopt the Equatable protocol

Related

Retrieving Data From Firebase Auto Id's - Firebase Swift

I am wanting to capture all the values in my childByAutoId in firebase. Essentially, it stores all the items that a person has shortlisted. However, I do not seem to be capturing this, and I assume it is because I am not calling the snapshot correctly to factor the auto id's.
Database:
userID
-> Favourited
-> Auto Id
-> itemName: x
-> Auto Id
-> itemName: x
-> Auto Id
-> itemName: x
Code:
func retrieveItems() {
guard let userId = Auth.auth().currentUser?.uid else { return }
let ref = Database.database().reference().child("users/\(userId)/Favourited")
ref.observe(.value, with: { (snapshot) in
if snapshot.childrenCount>0 {
self.favUsers.removeAll()
for likes in snapshot.children.allObjects as! [DataSnapshot] {
let likesObject = likes.value as? [String: AnyObject]
let itemName = likesObject!["itemName"]
let likesList = Names(id: likes.key, itemName: itemName as! String?)
self.favUsers.append(likesList)
}
} else {
print("not yet")
}
})
self.favList.reloadData()
}
Could someone have a look and let me know what I may be doing wrong? Thank you!
This happens because Firebase loads data asynchronously, and right now you're calling reloadData before the self.favUsers.append(likesList) has ever run.
The call to reloadData needs to be inside the close/completion handler that is called when the data comes back from Firebase:
ref.observe(.value, with: { (snapshot) in
if snapshot.childrenCount>0 {
self.favUsers.removeAll()
for likes in snapshot.children.allObjects as! [DataSnapshot] {
let likesObject = likes.value as? [String: AnyObject]
let itemName = likesObject!["itemName"]
let likesList = Names(id: likes.key, itemName: itemName as! String?)
self.favUsers.append(likesList)
}
self.favList.reloadData() // 👈 Move this here
} else {
print("not yet")
}
})
I also recommend checking out some of these answers asynchronous data loading in Firebase.

How do I get specific values from children in firebase using Swift 4?

My Firebase Database
More specifically, I have randomly generated children(Listings) and from those randomly generated Listings I would like to get the string value from the keys.
For example, if I wanted the Photo URL address, I would like to get the string value of the key "PhotoURL:".
Thank you in advance !
First you need to do is to import Firebase and then call a function from the Database class like so:
let ref = Database.database().reference().child("Listings")
You can call child recursively to go deeper into your tree
//.child("Listings").child("SomeListing").child("PhotoURL")
Then call observeSingleEvent to receive the values from firebase.
Your value is stored in the snapshot variable
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let listingsDictionary = snapshot.value as? [String: Any] else { return }
listngsDictionary.forEach({ (key, value) in
// Here you can iterate through it
})
}) { (err) in
print("Failed to fetch following listings:", err)
}
Here is the code to get child values from Listings. 
var ListArr = [ListModel]()
let ref = Database.database().reference().child("Listings")
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot)
guard let dictionary = snapshot.value as? [String : AnyObject] else {
return
}
let Obj = ListModel()
Obj.UID = snapshot.key
Obj.PhotoURL = dictionary["PhotoURL"] as? String
self.ListArr.append(Obj)
}, withCancel: nil)
}
You can set up the model class
class ListModel: NSObject {
var UID:String?
var PhotoURL:String?
}

Showing just one image at the time from database (Swift and Firebase)

First of all, I am new in this, so please do not make fun of me :)
Basically, I am trying to show and Image of a product but if the client refuses the product this item will not appear on his account. That is why I am creating another table Rejected (setAcceptedOrRejected) where I put the ID of the product and the Id of the client so I wont see the item he rejected before.
What I tried here it was to get the List (Good) with all the items and the (Bad) with the rejected items. Then compare it to display the picture of the item again.
My problem is that I want to show only 1 picture at the time, if the client refuses then it will show the next one and so on but it wont show that picture again.
I hope you can really help me with this one.
Thank you
func updateImage() {
createListProductsBad ()
var badnot = ""
for bad2 in listProductsBad{
badnot = bad2
}
Database.database().reference().child("Products").child(bad2)queryOrderedByKey().observe(.childAdded, with: { snapshot in
let userInfo = snapshot.value as! NSDictionary
let storageRef = Storage.storage().reference(forURL: profileUrl)
storageRef.downloadURL(completion: { (url, error) in
do {
let data = try Data(contentsOf: url!)
let image = UIImage(data: data as Data)
self.productPhoto.image = image
}
catch _ {
print("error")
}
})
})
}
func setAcceptedOrRejected() {
let notThankyou = [ "ProductID": ProductId,
"UserID": userUID
] as [String : Any]
self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.refProducts.child("Rejected").childByAutoId().setValue(notThankyou)
}
func createListProductsGood () {
Database.database().reference().child("Products").queryOrderedByKey().observe(.childAdded, with: { snapshot in
if !snapshot.exists() { return }
let userInfo = snapshot.value as! NSDictionary
let goodID = String(snapshot.key)
for prod in self.listProductsBad{
if (prod == goodID){
print("Not good **********************")
}else{
if (goodID != "" ){
self.listProductsGood.append(prod)
}
}
}
})
}
func createListProductsBad () {
Database.database().reference().child("Rejected").queryOrderedByKey().observe(.childAdded, with: { snapshot in
let userInfo = snapshot.value as! NSDictionary
let currentID = userInfo["UserID"] as! String
let badProduct = userInfo["ProductID"] as! String
if (self.userUID == currentID ){
self.listProductsBad.append(badProduct)
}
})
}
}
//These can also be swift's dictionaries, [String: AnyObject] or possibility arrays if done correctly. All depends on your style of programming - I prefer NSDictionaries just because.
let availableKeys: NSMutableDictionary = [:]
let rejectedKeys: NSMutableDictionary = [:]
//Might be a better way for you. Depends on what you are looking for.
func sortItems2() -> NSMutableDictionary{
for rejKey in rejectedKeys.allKeys{
//Removes if the rejected key is found in the available ones
availableKeys.remove(rejKey)
}
return availableKeys
}

Ambiguous Use of Subscript (Swift 3)

I am using the subscript in the following code incorrectly for this Firebase data pull, but I can't figure out what I am doing wrong. I get an error of Ambiguous use of subscript for the let uniqueID = each.value["Unique ID Event Number"] as! Int line.
// Log user in
if let user = FIRAuth.auth()?.currentUser {
let uid = user.uid
// values for vars sevenDaysAgo and oneDayAgo set here
...
let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)")
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in
if (snapshot.value is NSNull) {
print("user data not found")
}
else {
if let snapDict = snapshot.value as? [String:AnyObject] {
for each in snapDict {
// Save the IDs to array.
let uniqueID = each.value["Unique ID Event Number"] as! Int
self.arrayOfUserSearchHistoryIDs.append(uniqueID)
}
}
else{
print("SnapDict is null")
}
}
})
}
I tried to applying what I learned from this post, but I couldn't figure out what I am missing because I thought I was letting the compiler know what type of dictionary it is with the "as? [String:AnyObject]"
Any thoughts or ideas would be greatly appreciated!
My preferred way of dealing with data is to unwrap the FIRDataSnapshot as late as possible.
ref!.observe(.value, with: { (snapshot) in
for child in snapshot.children {
let msg = child as! FIRDataSnapshot
print("\(msg.key): \(msg.value!)")
let val = msg.value! as! [String:Any]
print("\(val["name"]!): \(val["message"]!)")
}
})
Taking Frank's feedback into account, here is the actual working code I used that follows that approach in case it's helpful.
// Log user in
if let user = FIRAuth.auth()?.currentUser {
let uid = user.uid
// values for vars sevenDaysAgo and oneDayAgo set here
...
let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)")
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in
if (snapshot.value is NSNull) {
print("user data not found")
}
else {
for child in snapshot.children {
let data = child as! FIRDataSnapshot
let value = data.value! as! [String:Any]
self.arrayOfUserSearchHistoryIDs.append(value["Unique ID Event Number"] as! Int)
}
}
})
}

IOS - Parsing objects from Firebase - Code running before download is completed

I am trying to parse data from Firebase into an array of objects, and upon completion display the text from the first object in the array. However, I can't work out/find a solution to stop the code continuing before the download is complete. So it proceeds to update the user's completion to true, without displaying the text. This is the function as is, the downloading and appending to array works fine, but it skips to displayNextInSeries() before it's finished...
func parseSeries (ref: String) {
FIRDatabase.database().reference().child("library").child("series").child(ref).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print(snap)
if let pushSeriesDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let push = PUSH_SERIES(pushKey: key, pushSeriesData: pushSeriesDict)
self.seriesArray.append(push)
}
}
}
})
print("\(ref) Series Count: \(self.seriesArray.count)")
displayNextInSeries()
}
The display next in series function sees the seriesArray.count = 0, so it doesn't update the texLbl:
func displayNextInSeries() {
if seriesProgress < seriesArray.count {
animateProgress(current: seriesProgress, total: seriesArray.count)
currentPUSH_SERIES = seriesArray[seriesProgress]
currentPUSH_SERIES.text = personaliseText(text: currentPUSH_SERIES.text)
textLbl.animateUpdate(currentPUSH_SERIES.text, oldText: previousText)
titleLbl.text = "\(currentPUSH_SERIES.title!)"
previousText = currentPUSH_SERIES.text
seriesProgress += 1
} else {
animateProgress(current: sessionProgress, total: sessionTarget)
titleLbl.text = ""
greetingPush()
seriesPlay = false
seriesProgress = 0
user.updateProgress(seriesName)
print(user.progress)
}
}
I may be doing something fundamentally wrong here. Your help is much needed and much appreciated! Thanks, Matt
The observeSingleOfEvent is an asynchronous call, calling the function inside the completionBlock will solve it,The problem is that your print function is being called even before observeSingleOfEvent is finished downloading data :-
func parseSeries (ref: String) {
FIRDatabase.database().reference().child("library").child("series").child(ref).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print(snap)
if let pushSeriesDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let push = PUSH_SERIES(pushKey: key, pushSeriesData: pushSeriesDict)
self.seriesArray.append(push)
print("\(ref) Series Count: \(self.seriesArray.count)")
displayNextInSeries()
}
}
}
})
}