【问题标题】:PDFKIT , Swift How to remove pdf (PDFDocument) from uitableviewPDFKIT,Swift 如何从 uitableview 中删除 pdf (PDFDocument)
【发布时间】:2018-03-13 14:53:47
【问题描述】:

我有这个下载PDF文件的代码:

var documents = [PDFDocument]()

  DispatchQueue.global(qos: .default).async(execute: {
            //All stuff here

            print("Download PDF");
            let url=NSURL(string: urlString);
            let urlData=NSData(contentsOf: url! as URL);

            if((urlData) != nil)
            {
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

                let fileName = urlString as NSString;

                let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

                let fileExists = FileManager().fileExists(atPath: filePath)

                if(fileExists){

                    // File is already downloaded
                    print("PDF Already Downloaded");
                }
                else{

                    //download
                    DispatchQueue.main.async(execute: { () -> Void in

                        print(filePath)
                        urlData?.write(toFile: filePath, atomically: true);
                        print("PDF Saved");

                        self.refreshData()
                    })
                }
            }
        })

现在我想从表格和文档目录中的 uitableview 中删除此文件如何使用索引路径行以及如何查找要删除的文件名

我知道我会在此处删除文件,但我不知道如何准确删除 documentDirectory 和 Table 中的 PDF

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)

    }

}

这是我的表格视图单元格

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BookshelfCell

        let document = documents[indexPath.row]
        if let documentAttributes = document.documentAttributes {
            if let title = documentAttributes["Title"] as? String {
                cell.title = title
            }
            if let author = documentAttributes["Author"] as? String {
                cell.author = author
            }

这是我的刷新数据部分

let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let contents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
    documents = contents.flatMap { PDFDocument(url: $0) }

【问题讨论】:

  • 如果您更好地解释您的表格视图设置,人们将能够更好地帮助您。
  • 你有什么建议我更新代码@Matthew Seaman?
  • 我看到你又添加了一些东西。应该更有帮助。
  • 可以找到一种从 NSDirectory @MatthewSeaman 中完全删除的解决方案吗?
  • 查看@theMikeSwan 的回答

标签: ios swift uitableview pdfkit nsdocumentdirectory


【解决方案1】:

您需要完成三个步骤才能正确删除文档并更新表格视图:

  1. 使用FileManagerremoveItem(at: URL)removeItem(atPath: String) 从磁盘中删除文件。 (请注意,这两种方法都会抛出,因此您需要使用 do-catch 块和 try,并且仅在该方法未抛出错误时才继续。)更新:如果您查看documentation for PDFDocument,您会发现除了您已经在使用的 documentAttributes,还有另一个可选属性 documentURL,它应该会为您提供删除它所需的确切内容。

  2. documents 中删除文档(您可以使用现有代码刷新整个数组,但删除单个项目更快)。 documents.remove(at: indexPath.row)

  3. 最后,您需要告诉表格视图删除有问题的行(您当然可以只重新加载整个表格视图,但删除单个单元格会更干净)tableView.deleteRows(at: [indexPath], with .fade)

如果你不熟悉 do-catch 块,这里有一些来自 Apple 关于 Swift 的书中的代码(请参阅下面的链接),稍微简化一下:

do {
    try makeASandwich()
    eatASandwich() // This only gets called if the line above worked
} catch {
    dealWithTheError() // This only gets called if makeASandwich() throws an error
}

旁注

Apple 在Swift Language 上有一个很棒的指南,如果您还没有这样做的话,我建议您至少阅读一下基础知识。这将使您对该语言有一个基本的了解。如果您也是编程新手,我建议您阅读 Apple 的 Learn to Code 系列,该系列在 Swift Playgrounds 应用程序中的 iPad 上免费。该系列将引导您了解所有编程基础知识,并为您提供工具来搜索 Apple 提供的文档并找到问题的答案。

我们都是从某个时候开始的,我们都必须先爬行,然后才能走路,然后才能跑。

【讨论】:

  • 谢谢@theMikeSwan 你能写一个准确的代码吗,因为我是新来的 swift
  • 我需要在这部分中找到从表格视图中删除的 url removeItem(at: URL) 你能帮我吗
  • 非常感谢我添加了这部分,documents.remove(at: indexPath.row) ,refreshData() 但是对于 removeItem(at: URL 我如何调用 FileManager 以及如何找到 fid如果可以为此编写代码,则添加的路径名或 url 地址对我来说太复杂了@theMikeSwan
  • 是否可以通过索引路径找到路径或 url (FileManager)
  • 您必须像获取documentAttributes 一样获取URL。而不是像你对属性使用if let documentAttributes = document.documentAttributes 那样使用if let documentURL = document.documentURL
猜你喜欢
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
相关资源
最近更新 更多