如何缓存文件(例如PDFDocument)以防止重新加载并提高用户体验-迅速?

时间:2018-11-01 07:23:50

标签: ios swift pdfkit nscache

我有一个带有收集视图的应用程序,该应用程序显示pdf文档的缩略图。当用户点击缩略图时,将显示新的UIViewController和PDFDocument。我试图缓存PDFDocument,以便应用程序不必每次都从服务器下载PDFDocument。我没有成功。我的代码每次都从服务器下载文件,而不是访问缓存。 我正在使用PDFKit呈现PDFDocument。下面是我的代码:

当用户在集合视图中点击缩略图时,以下UIViewController将被推入堆栈并显示PDFDocument:

 @IBOutlet weak var myPDFView: PDFView!
 let pdfCache = NSCache<NSString, PDFDocument>.init()

 func loadPDF(pdfURL: String) -> Void {

   // FIND IF PDF DOCUMENT IS ALREADY IN CACHE ON KEY 'pdfURL'
if let documentToCache = self.pdfCache.object(forKey: pdfURL as NSString){
    self.myPDFView.document = (documentToCache as! PDFDocument)
    self.myPDFView.displayMode = .singlePage
    self.myPDFView.autoScales = true
    print("PDF FROM CACHE!")
    return
}


 .....

// Not found in cache.  Download pdfDocument
Alamofire.request(pdfURL).responseData { response in

   if let data = response.data{

        DispatchQueue.main.async{

            let document = PDFDocument.init(data: data)

            // STORE PDF DOCUMENT TO CACHE
            self.pdfCache.setObject(document!, forKey: pdfURL as NSString)

            // DISPLAY PDF
            self.myPDFView.document = document
            self.myPDFView.displayMode = .singlePage
            self.myPDFView.autoScales = true
            print("PDF DOWNLOADED: \(pdfURL)")

        }
    }

}

}

0 个答案:

没有答案
相关问题