我有一个带有收集视图的应用程序,该应用程序显示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)")
}
}
}
}