Preview Documents Using QuickLook Framework
Posted By : Satish Thakur | 27-Feb-2020
If you want to preview documents file in your app, want to share or save the file in the memory, then there is no need to go for third-party library support.
Apple's QuickLook Framework lets us embed previewing files like iWork documents, Microsoft Office documents, PDFs, images, and more, all without writing much code.
Here is all about the basics as well as some advanced implementations. Let's Learn to present a variety of types of documents from within your app without reinventing the wheel, and make sure your custom file format works great with the built-in support offered by iOS.
The QuickLook Framework can be used very easily, and it can open specific types of documents for previewing. Those types are:
- iWork documents (Pages, Numbers and Keynote)
- Microsoft Office documents (supports Office 97 or any other newer version)
- PDF files
- Images
- Text files
- Rich-Text Format documents
- Comma-Separated Value files (CSV)
The Quick Look framework can be really useful if your app is dealing with files of any of the above file types and you want your users to be able to preview its content.
Here, I'm providing you the full demo code for the project. Please follow each and every line for better enhancement.
import UIKit
import QuickLook
class ViewController: UIViewController {
lazy var previewItem = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func displayLocalFile(_ sender: UIButton){
let previewController = QLPreviewController()
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDf.pdf")
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
@IBAction func displayFileFromUrl(_ sender: UIButton){
// Download file
self.downloadfile(completion: {(success, fileLocationURL) in
if success {
// Set the preview item to display
self.previewItem = fileLocationURL! as NSURL
// Display the file
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
} else {
debugPrint("Sorry, File can't be downloaded.")
}
})
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to display file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle.main.path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func downloadfile(completion: @escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: "https://images.apple.com/environment/pdf/Apple_Environmental_Responsibility_Report_2017.pdf")
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("filename.pdf")
// function to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
debugPrint("The file already exists at path")
completion(true, destinationUrl)
// and if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession method to download the data asynchronously
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
// after downloading your file from url you need to move it to your destination url
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
print("File moved to documents folder")
completion(true, destinationUrl)
} catch let error as NSError {
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
}
//MARK:- QLPreviewController Datasource
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}
Check the Apple Official Documentation. Follow this: https://developer.apple.com/
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Satish Thakur
Satish is working as a Mobile Application Developer. He is eager to learn about technologies and never neglect the opportunity. He believes in "Don't only dream, Work for it".