基于swift 3中的uitableview中的单元格选择删除文件



我想在Swift中制作一个表,该表将显示文件的名称,并允许用户通过单击单元格从documentDirectory删除它。

我是Swift的新手,并获得了无用的错误。这就是我在做的。首先,我正在为这些称为theurls的URL创建一个变量,并将其定义为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)
    }

使用此答案,我尝试使每个单元格对应于theurls的URL。我应该注意,这还没有文本标签,但是我想我稍后可以添加。

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let url = thedownloads[indexPath.row]
        print(url)
        try FileManager.default.removeItem(at: theurls[indexPath.row])

    }

这将抛出Errors thrown from here are not handled。我想将每个单元格设置为文本标签,然后在单击单元格时删除该项目。有一个更好的方法吗?

错误处理代码使用do-catch块:

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)
    }
}

最新更新