将 PDFDocument 作为 NSData 保存到 CoreData(如何将其转换为 NSData?)

Save PDFDocument to CoreData as NSData (how to convert it to NSData?)

所以这可能是一个微不足道的问题,但我无法让它发挥作用。 我想在将 pdf file 放到视图上后将其保存到 CoreData(使用 IOS' Drag&Drop 功能)

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
        session.loadObjects(ofClass: ComicBookPDFDocument.self) { (pdfItems) in
            let items = pdfItems as! [ComicBookPDFDocument]

            // "Cannot assign value of type 'ComicBookPDFDocument' to type 'NSData?'"
            self.file.data = items[0]
        }
}

ComicBookPDFDocument 只是子类 PDFDocument 以使其符合 NSItemProviderReading:

final class ComicBookPDFDocument: PDFDocument, NSItemProviderReading {

    public static var readableTypeIdentifiersForItemProvider: [String] {
        return [kUTTypePDF as String]
    }

    public static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> ComicBookPDFDocument {
        return ComicBookPDFDocument(data: data)!
    }
}

但是,我从 XCode:

得到这个编译器错误

Cannot assign value of type 'ComicBookPDFDocument' to type 'NSData?'

如何保存 PDFDocument 中的 pdf 数据?我在 Internet 或文档中找不到任何内容。

感谢您的帮助

好吧,我不知道我是怎么错过的,但它是:

items[0].dataRepresentation()

你做一件事,

尝试将 PDF 保存到文档目录中并将其路径保存在核心数据中。

这是保存到文档目录并从文档目录中获取的代码

class PDCache: NSObject {

static let sharedInstance = PDCache()

func saveData(obj: Data, fileName: String){

    let filename = getDocumentsDirectory().appendingPathComponent("\(fileName).pdf")
    do{
        try obj.write(to: filename, options: .atomic)
    } catch{
        print(error.localizedDescription)
    }
}

func getData(fileName: String) -> URL?{
    let fileManager = FileManager.default
    let filename = getDocumentsDirectory().appendingPathComponent("\(fileName).pdf")
    if fileManager.fileExists(atPath: filename.path){
        return URL(fileURLWithPath: filename.path)
    }
    return nil
}

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

要保存数据使用这个

    let data = Data()
    self.saveData(obj: data, fileName: "myPdfFile")

并获取文件 url 使用这个

let pdfUrl = self.getData(fileName: "myPdfFile")

试试这个,让我知道它是否适合你。