0

I would like to add a couple of images that are stored in variables to a QLPreviewController. The QuickLook datasource requires a fileURL which I'm not sure how to get for an image that is stored in a variable and not in disk or in the project.

Any pointers as to how I can solve this issue?

  • 1
    Did you try anything? you need to save image to local storage and get the path and pass it to `QLPreviewController` – Dilan May 17 '20 at 10:24
  • I don't really know how to use it properly. I was hoping to get an example of sorts to base my understanding on that. – krishna ravichander May 17 '20 at 11:47

1 Answers1

0

Below code can be used to to display image file from local and from URL in QLPreviewController.

import UIKit
import QuickLook

class ViewController: UIViewController {

    lazy var previewItem = NSURL()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func displayLocalFile(_ sender: UIButton){

        let previewController = QLPreviewController()
        // Set the preview item to display
        self.previewItem = self.getPreviewItem(withName: "bull.png")

        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 file

                DispatchQueue.main.async {
                   let previewController = QLPreviewController()
                    previewController.dataSource = self
                    self.present(previewController, animated: true, completion: nil)
                }


            }else{
                debugPrint("File can't be downloaded")
            }
        })
    }



    func getPreviewItem(withName name: String) -> NSURL{

        //  Code to diplay 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://developer.apple.com/wwdc20/images/hero/memoji/large/L7_2x.jpg")

        // 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.jpg")

        // 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)

            // if the file doesn't exist
        } else {

            // you can use NSURLSession.sharedSession 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 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
    }
}