swift - 如何在 ios 应用程序中缓存 PDFDocument - swift?
问题描述
我有一个带有集合视图的应用程序,它显示 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)")
}
}
}
}
解决方案
推荐阅读
- python - 为什么 sort_values() 与 sort_values().values 不同
- javascript - Heroku Web 进程在启动后 60 秒内无法绑定到 $PORT
- mariadb - 使用 SQL 将图像添加到数据库时出现问题
- node.js - 在 NodeJS 中操作原始 PCM 数据的缓冲区
- javascript - 在几个长度的字符串问题后自动填充破折号
- python - 不同的 Group By 在 SQLAlchemy 中不起作用
- git - gitignore 用于 git 添加
- typescript - 你可以在每个文件上启用 TypeScript 严格模式吗?
- javascript - 添加或编辑时单个可编辑的表格行
- awk - 使用awk将字符串添加到文件中的数字末尾?