Swift 如何缓存PDFDocument?

Swift 如何缓存PDFDocument?,swift,caching,ios-pdfkit,Swift,Caching,Ios Pdfkit,我正在尝试缓存从Firebase下载的PDFDocument,但它不起作用。 我正在使用PDFKit显示pdf 以下是我的代码: let cache = NSCache<NSString, PDFDocument>() func downloadPDF() { var thePdf = PDFDocument() if let cachedPdf = cache.object(forKey: "CachedPdf") { the

我正在尝试缓存从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)
            }

        }

     }
}
let cache=NSCache()
func下载pdf(){
var thePdf=PDFDocument()
如果让cachedPdf=cache.object(forKey:“cachedPdf”){
thePdf=缓存的dpdf
self.pdfView.document=thePdf
打印(“从缓存中检索”)
}否则{
//下载
guard let record=getRecord else{return}
让storage=storage.storage().reference(forURL:record.storageUrl)
storage.downloadURL{(url,错误)位于
如果错误==nil{
如果让getUrl=url{
thePdf=PDFDocument(url:getUrl)??PDFDocument()
self.cache.setObject(thePdf,forKey:“CachedPdf”)
self.pdfView.document=thePdf
打印(“下载”)
}
}否则{
guard let err=error else{return}
self.alert(标题:“Error”,消息:err.localizedDescription)
}
}
}
}
它从不从缓存中存储或检索任何内容,它总是下载pdf。

为什么缓存不适用于此文件?

您应该检查是否存在缓存对象
cache.object(forKey:“CachedPdf”)
在尝试下载pdf数据之前,我在
内部执行此操作,如果错误==nil
您需要在下载URL之前执行此操作,并将下载URL移动到缓存检查的else条件,使其看起来像您的缓存对象—它不同。您确定在下载视图控制器之前没有创建新的视图控制器吗?尝试创建一个单例(共享实例)并在那里添加缓存。看看这个哦,老兄,非常感谢。我认为缓存在默认情况下是单例的,所以问题是每次加载视图时我都会创建一个新的缓存。singleton建议修复了它。您应该检查是否存在缓存对象
cache.object(forKey:“CachedPdf”)
在尝试下载pdf数据之前,我在
内部执行此操作,如果错误==nil
您需要在下载URL之前执行此操作,并将下载URL移动到缓存检查的else条件,使其看起来像您的缓存对象—它不同。您确定在下载视图控制器之前没有创建新的视图控制器吗?尝试创建一个单例(共享实例)并在那里添加缓存。看看这个哦,老兄,非常感谢。我认为缓存在默认情况下是单例的,所以问题是每次加载视图时我都会创建一个新的缓存。单身汉的建议解决了这个问题。