首页 > 解决方案 > 如何缓存 PDF 文档?

问题描述

我正在尝试缓存从 Firebase 下载的 PDFDocument,但它不工作。我正在使用 PDFKit 来显示 pdf。

这是我的代码:

    let cache = NSCache<NSString, PDFDocument>()

    func downloadPDF() {

    var thePdf = PDFDocument()

    if let cachedPdf = cache.object(forKey: "CachedPdf") {
         thePdf = cachedPdf
         self.pdfView.document = thePdf
         print("retrieved from cache")
     } else {

        //download
        guard let record = getRecord else {return}
        let storage = Storage.storage().reference(forURL: record.storageUrl)
        storage.downloadURL { (url, error) in
            if error == nil {

                if let getUrl = url {
                    thePdf = PDFDocument(url: getUrl) ?? PDFDocument()
                    self.cache.setObject(thePdf, forKey: "CachedPdf")
                    self.pdfView.document = thePdf
                    print("downloaded")
                }

            } else {
                guard let err = error else { return }
                self.alert(title: "Error", message: err.localizedDescription)
            }

        }

     }
}

它从不存储或从缓存中检索任何内容,它总是下载 pdf。
为什么缓存不适用于此文件?

标签: swiftcachingios-pdfkit

解决方案


推荐阅读