【问题标题】:loading file url from documentDirectory to table view将文件 url 从 documentDirectory 加载到表视图
【发布时间】:2017-11-05 20:03:11
【问题描述】:

我一直在尝试将文件加载到文档目录中以显示在 uitableview 上并使用 quickview 读取它们

var fileURLs: [NSURL] = []

每次我运行应用程序时,它都会在这一行出错,因为 "index out of range" on fileURLs[indexPath.row]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if QLPreviewController.canPreview(fileURLs[indexPath.row]) {
        quickLookController.currentPreviewItemIndex = indexPath.row
        navigationController?.pushViewController(quickLookController, animated: true)
    }
}

fileURLs 数组被下面的方法附加

private func prepareFileURLS() {
    let fileManager = FileManager.default
    let path = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last! as NSURL
    let fileName = String(describing: path.lastPathComponent)
    let pathString = String(describing: path.absoluteURL)
    fileNames.append(fileName)

    if FileManager.default.fileExists(atPath: pathString) {
        fileURLs.append(path as NSURL)
        print(fileURLs)
    }
}

每次检查的结果都是一个空数组,并且只返回一个文档路径而不是文件路径本身

[]
Optional(file:///Users/N/Library/Developer/CoreSimulator/Devices/EC72CD97-87F4-478E-967C-6BA135B2EC6C/data/Containers/Data/Application/0778931B-77DD-4CE8-92BF-E9A8002F901D/Documents/)

当我手动检查文件夹时,它们是其中的一个文件。 有人知道上面的代码有什么问题吗?

添加了**表上的文件显示非常好,因为它从模型文件中加载名称和其他数据,但无法查看

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    //tableView.reloadData()
    return csvFiles.count
}

这里是数据模型

class CSVData {

// MARK: Properties
var name: String
var descriptions: String
var photo: UIImage?
var url: NSURL


// MARK: Init
init?(name: String, descriptions: String?, photo: UIImage?, url: NSURL){
    // init should fail if there is no name
    if name.isEmpty {
        return nil
    }

    self.name = name
    self.descriptions = descriptions ?? ""
    self.photo = photo
    self.url = url
}

}

【问题讨论】:

  • 您需要显示您的 numberOfRowsInSecrion 函数,因为您似乎已经告诉 tableview 行数多于数组中的元素数。
  • @Paulw11 我刚刚添加了更多信息。该文件完美地显示在桌子上,但无法查看。我猜是因为它无法访问它的网址。数据模型还包括它的 url,但我不知道如何使用它
  • absoluteURL 不返回路径。要获取 url 路径,您应该获取其 path 属性。如果您传递 url absoluteString,fileExists(atPath:) 将始终失败。 FileManager.default.fileExists(atPath: url.path) 。并且不要使用String(describing:)
  • 顺便说一句,你应该使用 URL 而不是 NSURL,因为 Swift 3

标签: ios swift uitableview uiview qquickview


【解决方案1】:

fileManager.urls 返回域上的目录数组,而不是该目录中的文件数组。要获取文件路径,您应该使用 FileManager 的 contentsOfDirectory。见https://stackoverflow.com/a/27722526/6835150

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2017-07-10
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多