如何在iOS上访问创建的pdf文档?

时间:2016-10-27 13:34:40

标签: ios swift

我的应用有一个创建pdf文件的动作。在模拟器上创建文件后,我可以在Mac上访问创建的文件但在iPhone上我不能。即使我搜索过但找不到。在Acrobat Reader上都没有。

那么这个创建的pdf文件怎么办?我应该将其转换为ePub还是其他什么?

这是我创建pdf的代码:

func createPdfFromView(_ imageView: UIImageView, saveToDocumentsWithFileName fileName: String)
{
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, imageView.bounds, nil)
    UIGraphicsBeginPDFPage()

    let pdfContext = UIGraphicsGetCurrentContext()

    if (pdfContext == nil)
    {
        return
    }

    imageView.layer.render(in: pdfContext!)
    UIGraphicsEndPDFContext()


}
@IBAction func createPdfAction(_ sender: UIButton) {

    createPdfFromView(ImageDisplay, saveToDocumentsWithFileName: "")
}

1 个答案:

答案 0 :(得分:1)

将PDF数据写为本地路径中的文件

private var pdfData: NSMutableData!
private var filPath: NSString!
private var docController: UIDocumentInteractionController!

func writeDataAsFile()
{
    //Search for local path
    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let directoryPath = paths[0] as NSString

    //Appending file name to be saved in directory path
    filPath = directoryPath.appendingPathComponent("TestPDF.pdf") as NSString!

    //Check file is already exist in path
    let isFileExists = FileManager.default.fileExists(atPath: filPath as String)

    if(!isFileExists)
    {
        //pdfData is NSData/NSMutableData, Write to the filepath
        pdfData.write(toFile: filPath as String, atomically: true)
    }
}

UIDocumentInteractionController提供应用内支持,用于管理用户与本地系统中文件的交互

@IBAction func goPDF(sender: UIButton) {

    docController = UIDocumentInteractionController.init(url: NSURL.fileURL(withPath: filPath as String, isDirectory: true))
    docController.delegate = self
    docController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
}

UIDocumentInteractionControllerDelegate处理文档互动

func documentInteractionController(_ controller: UIDocumentInteractionController, willBeginSendingToApplication application: String?) {
    print("willBeginSendingToApplication")
}

func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
    print("didEndSendingToApplication")
}

func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
    print("documentInteractionControllerDidDismissOpenInMenu")
}

在ViewController中使用委托应该像这样符合UIDocumentInteractionControllerDelegate,例如,在ViewController中

import UIKit

class FirstViewController: UIViewController, UIDocumentInteractionControllerDelegate {
}

对于在iBooks中打开PDF,菜单将提供“使用iBooks导入”选项。此选项将导致在导入后在iBooks中打开PDF。