0

I'd like to make a table in Swift that will show the name of a file and allow the user to delete it from the documentDirectory by clicking on a cell.

I'm new to Swift and getting a not useful error. Here's what I am doing. First, I am creating a variable for these URLs called theurls and defining it as all contents of the documentDirectory.

class DownloadTableViewController: UITableViewController {

var theurls = [URL]()


override func viewDidLoad() {
    super.viewDidLoad()

    // Get the document directory url
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    do {
        // Get the directory contents urls (including subfolders urls)
        let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
        // print(directoryContents)
        theurls = directoryContents

    } catch {
        print(error.localizedDescription)
    }

Using this answer, I try and make each cell correspond to a URL from theurls. I should note that this doesn't have text labels yet, but I assume I can add that later.

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let url = thedownloads[indexPath.row]
        print(url)

        try FileManager.default.removeItem(at: theurls[indexPath.row])


    }

This throws Errors thrown from here are not handled. I'd like to set each cell as a text label and then remove that item when the cell is clicked. Is there a better way to do this?

darkginger
  • 652
  • 1
  • 10
  • 38

1 Answers1

2

Error handling code use a do-catch block:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let url = thedownloads[indexPath.row]
    print(url)

    do {
        try FileManager.default.removeItem(at: theurls[indexPath.row])
    } catch {
        print(error)
    }
}
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24
  • You are welcome ;) check [Apple doc](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html) for handling errors. – Francesco Deliro Feb 15 '18 at 07:33