class ViewController: UIViewController {
let quickLookController = QLPreviewController()
override func viewDidLoad() {
super.viewDidLoad()
quickLookController.dataSource = self
quickLookController.delegate = self
}
@IBAction func buttonAction(_ sender: Any) {
present(quickLookController, animated: true, completion: nil)
quickLookController.reloadData()
quickLookController.refreshCurrentPreviewItem()
}
}
extension ViewController: QLPreviewControllerDataSource,QLPreviewControllerDelegate {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let path = Bundle.main.path(forResource: "AppCoda-Ppt.ppt", ofType: nil)
let url = NSURL(fileURLWithPath: path!)
return url
}
}
4
votes
3 Answers
4
votes
0
votes
Answer from @Thomas is correct (THANK YOU!) For Swift 3 you can do something like this in the previewItemAt:index method to cache the file on demand:
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
guard let CacheDirURL = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {
print("Can't get cache dir URL")
return NSURL(fileURLWithPath: "FILE_NOT_FOUND")
}
let fileUrl = CacheDirURL.appendingPathComponent("cachedFileName.pdf")
if !FileManager.default.fileExists(atPath: fileUrl.path) {
if let sourceUrl = Bundle.main.url(forResource: "Pioneer_UAS_Policy_Aug_2016", withExtension: "pdf") {
print("Copying file from bundle \(sourceUrl.path)")
try? FileManager.default.copyItem(at: sourceUrl, to: fileUrl)
}
}
return NSURL(fileURLWithPath: fileUrl.path)
}