【问题标题】:Save PDFDocument to CoreData as NSData (how to convert it to NSData?)将 PDFDocument 保存为 CoreData 作为 NSData(如何将其转换为 NSData?)
【发布时间】:2018-05-19 11:09:46
【问题描述】:

所以这可能是一个微不足道的问题,但我无法让它发挥作用。 我想在将 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 中得到这个编译器错误:

无法将类型“ComicBookPDFDocument”的值分配给类型“NSData?”

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

感谢您的帮助

【问题讨论】:

    标签: ios swift pdfkit


    【解决方案1】:

    好吧,我不知道我是怎么错过的,但就是这样:

    items[0].dataRepresentation()
    

    【讨论】:

    • 请为您的回答提供一些背景信息。我在上面的原始示例代码中没有看到任何“items”。我正在尝试做同样的想法,但不知道我应该在哪里使用这条神奇的线路:items[0].dataRepresentation()
    • @HirsuteJim 实际上在我的问题的示例代码中定义了一个 items 变量
    【解决方案2】:

    你只做一件事,

    尝试将 PDF 保存到 Document Directory 中,并将其路径保存在 Core-Data 中。

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

    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")
    

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

    【讨论】:

    • 谢谢,但这并没有解释如何首先获得Data()。这是我唯一的问题。 (另外,我找到了答案:有一个属性dataRepresentation()。见我上面的答案)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多