Search code examples
iosswiftquicklookdocument-preview

Present preview of downloaded file directly in app


My application have file download option which downloads the file using alamofire download method. When the download completes i need to present the preview of the file without saving it to internal/cloud storage. How can i achieve this whatsapp like function that shows the preview after downloading the file.

func downloadFile(fileUrl: URL) {
    let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)

    Alamofire.download(fileUrl, to: destination)
        .response(completionHandler: { (downloadResponse) in
            self.dic.url = downloadResponse.destinationURL
            self.dic.uti = downloadResponse.destinationURL!.uti
            let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
            self.dic.presentOpenInMenu(from: rect, in: self.view, animated: true)
        })
}

Solution

  • To present a preview of a file use Apple’s QuickLook framework that lets you embed previewing for a huge range of file types, including iWork documents, Microsoft Office documents, PDFs, images, and more, all without writing much code.

    First, import the QuickLook framework, then make your view controller conform to the QLPreviewControllerDataSource protocol.

    Reference:

    1. https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller

    2. https://github.com/gargsStack/QLPreviewDemo

    3. https://www.appcoda.com/quick-look-framework/

    Code:

    class ViewController: UIViewController {
        var previewItem = URL!
    
        func downloadFile(fileUrl: URL) {
            let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
    
            Alamofire.download(fileUrl, to: destination)
            .response(completionHandler: { (downloadResponse) in
    
                let previewController = QLPreviewController()
                previewController.dataSource = self
                self.previewItem = downloadResponse.destinationURL
                self.present(previewController, animated: true, completion: nil)
            })
        }
    }
    
    extension ViewController: QLPreviewControllerDataSource {
        func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
            return 1
        }
    
        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
           return self.previewItem as QLPreviewItem
        }
    }