我制作了一个 pdf 创建器应用程序。创建 pdf 文件后,我想在 tableview
上显示创建的文件。我创建了 Tableview Controller 和 DocumentDirectoryTableTableViewController
。毕竟我不知道该怎么做。
我找到了 this和 this问题,但我无法将其实现到我的代码中。
最好添加我的保存文件代码:
// 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/