【问题标题】:Display and open saved files on TableView在 TableView 上显示和打开保存的文件
【发布时间】:2016-11-30 11:47:20
【问题描述】:

我制作了一个 pdf 创建器应用程序。创建 pdf 文件后,我想在 tableview 上显示创建的文件。我创建了 Tableview Controller 和DocumentDirectoryTableTableViewController。毕竟我不知道该怎么做。

我发现了thisthis 的问题,但我无法在我的代码中实现它。

最好添加我的代码来保存文件:

        // 5. Save PDF file
    let path = "/MyApp/PdfFiles/MyPDF.pdf"
    pdfData.write(toFile: path, atomically: true)
    print("open \(path)") // command to open the generated file

更新: 我也可以通过这个函数获取 App Directory 并使用它:

    func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

let path = "\(getDocumentsDirectory())MyApp.pdf"

【问题讨论】:

  • 我的问题是我无法匹配这些代码。我的意思是我保存在这里:/MyApp/PdfFiles/MyPDF.pdf 但我不知道如何将此目录实现到代码中。 print("open \(path)") 怎么了?我是新开发者,请多多包涵。 @KrishnaCA
  • 我刚刚检查了您更新的代码。你到底在什么时候被困住了?此外,您的初始路径“/MyApp/PdfFiles/MyPDF.pdf”不正确。因为 iOS 文件路径以不同的方式开始。您在更新的代码中执行此操作的方式是正确的
  • @KrishnaCA 问题是:运行应用程序时,我在 tableview 上看不到任何文件。即使使用更新的代码,我也看不到任何文件。
  • 您是否正确读取文件?
  • @KrishnaCA 我应该在哪里实现我链接到 DocumentDirectoryTableTableViewController.Swift 的代码?我想我有问题。

标签: ios swift uitableview


【解决方案1】:

如果您尝试存储的 pdf 文件有 NSData,并且如果您希望用户访问它,则可以使用以下方式编写它:

func writePDF(data: NSData, to Name:String) -> Bool {

    let pdfData:NSData = data

    let pdfPaths:[String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    var pdfPath = pdfPaths[0]
    pdfPath.append("_\(Name).pdf")
    let result:Bool = pdfData.write(toFile: pdfPath, atomically: true)

    return result
}

如果您想在您的应用程序中以编程方式读取 pdf 文件,前提是您将其存储在上述路径中。可以这样做:

func readPDF(Name: String) {

    let pdfPaths:[String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    var pdfPath = pdfPaths[0]
    pdfPath.append("_\(Name).pdf")
    if let pdfData:NSData = NSData(contentsOfFile: pdfPath) { // verifying pdf exists in this path
        let documentController: UIDocumentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: pdfPath))
        documentController.delegate = self
        documentController.presentPreview(animated: true)
    }
}

// the below delegate function for `UIDocumentInteractionController` is necessary for it to present in the current `UIViewController`
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    return self
}

【讨论】:

  • 我正在尝试函数readPDF。调用函数时Name: String应该写什么?
  • 您是否保存了您的 pdf,即写在某处?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
相关资源
最近更新 更多