【问题标题】:Delete file based on cell selection in UITableView in Swift 3在 Swift 3 中基于 UITableView 中的单元格选择删除文件
【发布时间】:2018-02-15 07:15:46
【问题描述】:

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

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

使用this answer,我尝试使每个单元格对应于来自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。我想将每个单元格设置为文本标签,然后在单击单元格时删除该项目。有一个更好的方法吗?

【问题讨论】:

  • 我尝试你在我的机器上编码它的工作正常,你得到什么错误?你能告诉我吗?

标签: ios swift uitableview


【解决方案1】:

错误处理代码使用 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)
    }
}

【讨论】:

  • 不客气 ;) 检查Apple doc 处理错误。
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2015-04-10
  • 1970-01-01
相关资源
最近更新 更多