iosswiftuitableviewnsdocumentdirectory

Swift - Delete cell from UITableView


I am following this code to remove data from UITableView

var recordedAudioFilesURLArray = [URL]()
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            recordedAudioFilesURLArray.remove(at: indexPath.row)
            self.tableView.reloadData()
        }
    }

When I swipe left to a particular cell, the cell remove from UITableView. Thats great. But when I close my app and again relaunch my app, deleted cells are appeared. Audio Files are stored in Document Directory.


Solution

  • Use that URL array to remove the file from DocumentDirectory then remove the object from Array.

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
    
            //First remove file from DocumentDirectory
            try? FileManager.default.removeItem(at: recordedAudioFilesURLArray[indexPath.row]) 
    
            //Remove object from array
            recordedAudioFilesURLArray.remove(at: indexPath.row)
    
            //Reload tableView
            self.tableView.reloadData()
        }
    }