ios - 在 TableView 上显示和打开保存的文件

标签 ios swift uitableview

我制作了一个 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

更新: 我还可以通过此功能获取应用程序目录并使用它:

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

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

最佳答案

如果您有 NSData 用于您要存储的 pdf 文件,并且如果您希望用户访问它,您可以使用以下代码编写它:

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
}

关于ios - 在 TableView 上显示和打开保存的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40887598/

相关文章:

ios - 在两个 View Controller 之间传递数据不起作用

ios - 在文本字段中输入警报而不是键盘 ->光标停留在文本字段Swift2中

ios - 在隐藏的导航栏上具有不同行为的 ViewController

ios - Swift 中 ScrollView 的问题

ios - 未调用 BLE 外设委托(delegate)

iOS:当应用程序在后台时如何保持 TCP 套接字和 NSNetService 工作

ios - 从 Xcode 将 Ad Hoc 应用程序安装到设备需要重启手机

ios - 如何在 IOS 中获得类似于 IMEI 的标识字符串

ios - UITextField 在 UIButton 触摸时退出第一响应者

具有内部 CollectionView 的 TableViewCell 上的 iOS 可访问性