I have an app with a collection view that displays thumbnails of pdf documents. When a user taps on the thumbnail a new UIViewController is presented along with the PDFDocument. I am trying to cache the PDFDocument so that the app does not have to download the PDFDocument from the server every time. I have not been successful. My code downloads the file every time from the server instead of accessing the cache. I am using PDFKit to present the PDFDocument. Below is my code:
When a user taps on a thumbnail in the collection view, the following UIViewController is pushed onto the stack and displays the 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)")
}
}
}
}