How to delete tableView cell and remove data from firebase
To delete a node in Firebase, first establish the path to that node by creating a reference to it, and then removeValue on that reference (or set the ref to nil which also removes it)
In brief
let eventToDelete = dataSource[indexPath.row] //get the event from the dataSource
let firebaseKey = eventToDelete.eventId //assuming the eventId is the node key
let eventRef = my_firebase.child("events").child(firebaseKey)
eventRef.removeValue() //or eventRef.setValue(nil)
Delete tableView cell and remove data from firebase
Speaking at a high level, your tableView is backed by a dataSource, typically an array, which is the source for the content displayed in the tableView.
var userCommentArray = [UserComment]()
you should be loading data from Firebase and storing that data in the array as UserComment objects
class UserComment {
var firebaseKey = ""
var commentText = ""
var uid = ""
}
the firebase_key property is the key to the node in Firebase, shown as -MH_xxxx
in the screenshot and then the commentText and uid are is the child data of that node.
The indexes of the elements in the array match what's being shown in the tableView, so row0 matches the array index 0, row 1 matches the array index 1 etc.
When the user deletes row 1, you know that's index 1 in the array. read the object, get it's firebaseKey and then delete it from firebase, updating the array accordingly and then reloading your UI.
See my answer to your Other Question for details on that process.
delete tableView cell, and remove data from firebase
First, you don't delete a tableViewCell
from Firebase, but you can remove the data from Firebase that you pull to populate your tableView
.
Second, what you're doing wrong is trying to get a class value of ref
from an array.
Third, after deleting the data from the web, you'll still need to remove the cell from the table which your code looks like it will do just fine but I'm putting it here for completeness.
To delete a value from Firebase you need to create a reference and then process things from there. Like this :
let ref = Database.database().reference(fromURL: yourProjectURL)
let groupRef= ref.child("groups").child(groupsArray[indexPath.row].key)
// ^^ this only works if the value is set to the firebase uid, otherwise you need to pull that data from somewhere else.
groupRef.removeValue()
Then delete the item from the array:
groupsArray.remove(at: indexPath.row)
And delete the row from the
tableView
:
tableView.deleteRows(at: [indexPath], with: .automatic)
Everything should look like this :
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let ref = Database.database().reference(fromURL: yourProjectURL)
let groupRef= ref.child("groups").child(groupsArray[indexPath.row].key)
// ^^ this only works if the value is set to the firebase uid, otherwise you need to pull that data from somewhere else.
groupRef.removeValue()
groupsArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
how to delete firebase with tableView cell SWIFT
The code in the question won't actually remove anything from the posts node.
Database.database().reference().child("posts").child("uid").removeValue()
^^^^^
there is no child node that's has a key of the literal string "uid"
If there were a child node with a key of "uid", only that child would be removed. For example.
posts
post_0
author: "test_0"
post_1
author: "test_1"
uid
author: "test_2"
post_2
author: "test_3"
If the structure looked like that and the code was run, it would remove the node that had a key of "uid"
posts
post_0
author: "test_0"
post_1
author: "test_1"
post_2
author: "test_3"
EDIT:
Supposed I wanted to delete the post_1 node from posts. Here's how that would be done (there are other ways as well)
Database.database().reference().child("posts").child("post_1").removeValue()
EDIT 2: the good stuff
Based on comments, the actual issue is the OP doesn't know how to get to the specific node they want to delete. Here are two options
1) Query for the node (not recommended)
With this option, you would need to query for the node by some value. The key here is the value must exist within the node. So in my above structure query for the node where author = "test_1". The downside of this is there could be multiple authors "test_1" so this option has limitations
2) Recommended
Change your Swift model to also store the node key. It's not outlined in the question but typically a tableView is backed by a dataSource, an array, and that array contains models which match your Firebase data.
I'm addressing this at a high level with pseudo-code as there's not enough code in the question know specifics.
In this case it appears to be a listing of posts so a model would be
class PostClass {
var post_id = ""
var post_text = ""
var author_uid = ""
var photo_url = ""
}
then the dataSource array to store it
var postsArray = [PostClass]()
then when Firebase is read, create the object and store the key along with the data in each object
postsNode.observe.... { snapshot in
let post = PostClass()
post.post_id = snapshot.key //<- this is the important part
post.post_text = snapshot.childSnapshot("post_text") as? String ?? "No Text"
....
self.postArray.append(post)
}
So now all of the data from each node is stored and when it comes time to delete, just read that object from the dataSource, get the post_id and delete
let post = self.postArray[index of row to delete]
let postId = post.post_id
Database.database().reference().child("posts").child(postId).removeValue()
how to delete cell and data in firebase and swift 3
You are only deleting data for your UITableView
. The logic that you need is to delete from your UITableView
and Fireabase Database
. As the firebase docs says you can either call removeValue
, or setValue
to nil or updateChildValues
.
To make the deletion easier, I'd save the key of the object where the data is saved (snapshot.keys
), so when you want to delete you can just get that key and perform actions.
How do I delete a cell from tableview
Without seeing all of the code it's hard to provide a specific example but let me cover this at a high level.
Suppose we have a posts class object
class PostsClass {
var docId = ""
var post = ""
}
and an class array (aka a 'dataSource') to store them in
var postsArray = [PostsClass]()
The first step is to load all of the posts from Firebase, storing the docId and post text in each class and then store the class in the dataSource array.
myFirebase.getDocuments { doc...
for doc in documents { //iterate over the documents and populate the array
let post = PostClass(populate with data from firebase)
self.postsArray.add(post)
}
}
the dataSouce array will look like this
postsArray[0] = some post
postsArray[1] = another post
etc, and all of that is displayed in a tableView.
The user then decides to delete the post at row 1. So they swipe row one, which fires a tableView delegate event letting the app know the index of the swiped row.
Step 1: You then get that post from the array based on the swiped row index
let postToDelete = self.postsArray[swiped index]
let docIdToDelete = postsToDelete.docID
Step 2: then remove it from the array
self.postsArray.deleteRow(atIndex: swiped index)
Step 3: then delete it from Firebase.
self.my_firebase.collection("posts").document(docIdToDelete).delete {....
Note that the func tableView:tableView:commit editingStyle
will present the editing style of .delete
when the row is supposed to be deleted and also provide the index in indexPath.row
How to delete files from Firebase Storage and Table View - Swift
UPDATE This is how i managed to solve my issue for deleting files in Storage the reference in Firestore and the downloaded file also i remove from the table directly.
This help me: Swift Firestore - Delete Table Cell and Remove Document from Firestore
let localFileName = fileURLs[indexPath.row].lastPathComponent
var storageURL = ""
db.collection(K.FStore.customerCollectionName).document(documentListRef)
.collection(K.FStore.docCollectionName).whereField("fileName", isEqualTo: localFileName).getDocuments{ snapshot, error in
if let error = error {
print(error.localizedDescription)
} else {
for document in snapshot!.documents {
//print("\(document.documentID) => \(document.data())")
let data = document.data()
if let url = data["url"] as? String{
storageURL = url
}
if document.documentID != "" {
let storageRef = Storage.storage().reference()
//Get the sotrage reference from firesore
let fileRef = storageRef.child(storageURL)
//Delete the specific file in firestore
fileRef.delete { error in
if let error = error{
print("Error while deleting the document \(error)")
} else{
print("File deleted successfully")
//Delete the document from firestore
self.db.collection(K.FStore.customerCollectionName).document(self.documentListRef)
.collection(K.FStore.docCollectionName).document(document.documentID).delete(){ err in
if let err = err {
print("Error while deleting the document: \(err)")
} else {
//Get the local file path
let docsurl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let tempDirPath = docsurl.appendingPathComponent("\(K.FStorage.documentFolderName)/\(self.documentListRef)/\(localFileName)")
do {
//Delete the local file from path
try FileManager.default.removeItem(at: tempDirPath)
} catch { print(error) }
print("Document successfully deleted")
//Remove the file from the TableView
self.fileURLs.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
Related Topics
What's The Difference Between Nsusernotification and Unusernotification in Macos
Is There a Difference Between Global Initialization Vs Viewdidload Initialization in Swift
Swift: Forward Keystrokes to a Different Process
Nsextensionpointidentifier Error Only on Real Device
How to Put Gamecenter on Application with Swift
How to Get The Nearest Int Floored from a Sqrt of an Int
Stripe API Response: The Data Couldn't Be Read Because It Isn't in The Correct Format
Error Domain=Nscocoaerrordomain Code=3840 "Invalid Value Around Character 0
Swiftui: Make Remaining Area of List Item Detect Clicks
Swiftui: Why Doesn't Observedobject Work in Appdelegate
Create Record Only If Parent Exists in Vapor Using Fluent
Swift Optionals Best Practices
Why Are Implicitly Unwrapped Variables Now Printing Out as Some(...) in Swift 4.1