iOS PDFKit 不会写入

hea*_*che 2 pdf ios swift

import UIKit\nimport PDFKit\n\nclass ViewController: UIViewController {\n\n    @IBOutlet weak var pdfView: PDFView!\n\n    lazy var pdfDoc:PDFDocument? = {\n        guard let path = Bundle.main.path(forResource: "6368", ofType: "pdf") else {return nil}\n        let url = URL(fileURLWithPath: path)\n        return PDFDocument(url: url)\n    }()\n\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        self.setupPDFView()\n        self.save()\n    }\n\n    func setupPDFView() {\n        //Setup and put pdf on view\n        pdfView.autoScales = true\n        pdfView.displayMode = .singlePageContinuous\n        pdfView.displayDirection = .horizontal\n        pdfView.document = pdfDoc\n\n        self.add(annotation: self.circleAnnotation(), to: 0)\n    }\n\n    func add(annotation: PDFAnnotation, to page:Int){\n        self.pdfDoc?.page(at: page)?.addAnnotation(annotation)\n    }\n\n    func circleAnnotation()->PDFAnnotation {\n        let bounds = CGRect(x: 20.0, y: 20.0, width:200.0, height: 200.0)\n        let annotation = PDFAnnotation(bounds: bounds, forType: .circle, withProperties: nil)\n        annotation.interiorColor = UIColor.black\n        return annotation\n    }\n\n    func save() {\n        //Save to file\n        guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {return}\n        let data = pdfView.document?.dataRepresentation()\n        do {\n            if data != nil{try data!.write(to: url)}\n        } \n        catch {\n            print(error.localizedDescription)\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这只是简单的PDFKit代码,应该向 pdf 的第一页添加一个圆圈并将其保存到文档目录中。除了保存之外,一切正常。当我断点之后let data = ..。显示有数据,但是有两个错误:

\n\n
\n

1) 2018-12-18 05:10:28.887195-0500 PDFWriteTest[21577:1331197]\n [未知进程名称]无法加载\n /System/Library/PrivateFrameworks/CorePDF.framework/Versions/A/CorePDF

\n
\n\n
    \n
  • 无论我是否发现错误并打印,都会显示这一点
  • \n
\n\n
\n

2) 文件\xe2\x80\x9cDocuments\xe2\x80\x9d 无法\xe2\x80\x99 保存在文件夹\n \xe2\x80\x9cD3E23B05-92...\xe2\x80\x9d 中。

\n
\n\n
    \n
  • 这是从 error.localizedDescription 打印的内容
  • \n
\n\n

使用 PDFKit 可以解决此问题(将 PDF 数据保存到文件)吗?

\n

vad*_*ian 6

您不能将数据直接写入代表文件Documents夹的 URL,您必须指定(并附加)文件名。

func save(filename : String) {
    //Save to file
    guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
          let data = pdfView.document?.dataRepresentation() else {return}
    let fileURL = url.appendingPathComponent(filename)
    do {
        try data.write(to: fileURL)
    } catch {
        print(error.localizedDescription)
    }
}
Run Code Online (Sandbox Code Playgroud)