How to display remote document using QLPreviewController in swift

后端 未结 2 956
别跟我提以往
别跟我提以往 2020-11-30 14:24

I am using QLPreviewController to preview documents. But i do not know how to display document stored on a server.

2条回答
  •  一生所求
    2020-11-30 14:47

    You can't. QuickLook only works for local resource files. You would need to download the data asynchronously first, save it to the document directory or to a temporary folder and present the QLPreviewController from the main thread when finished:

    edit/update:

    Xcode 11.3.1 • Swift 5.1


    ViewController.swift

    import UIKit
    import QuickLook
    
    class ViewController: UIViewController, QLPreviewControllerDelegate, QLPreviewControllerDataSource {
        let previewController = QLPreviewController()
        var previewItems: [PreviewItem] = []
        override func viewDidLoad() {
            super.viewDidLoad()
            let url = URL(string:"https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf")!
            quickLook(url: url)
        }
        func numberOfPreviewItems(in controller: QLPreviewController) -> Int { previewItems.count }
        func quickLook(url: URL) {
            URLSession.shared.dataTask(with: url) { data, response, error in
                guard let data = data, error == nil else {
                    //  in case of failure to download your data you need to present alert to the user
                    self.presentAlertController(with: error?.localizedDescription ?? "Failed to download the pdf!!!")
                    return
                }
                // you neeed to check if the downloaded data is a valid pdf
                guard
                    let httpURLResponse = response as? HTTPURLResponse,
                    let mimeType = httpURLResponse.mimeType,
                    mimeType.hasSuffix("pdf")
                else {
                    print((response as? HTTPURLResponse)?.mimeType ?? "")
                    self.presentAlertController(with: "the data downloaded it is not a valid pdf file")
                    return
                }
                do {
                    // rename the temporary file or save it to the document or library directory if you want to keep the file
                    let suggestedFilename = httpURLResponse.suggestedFilename ?? "quicklook.pdf"
                    var previewURL = FileManager.default.temporaryDirectory.appendingPathComponent(suggestedFilename)
                    try data.write(to: previewURL, options: .atomic)   // atomic option overwrites it if needed
                    previewURL.hasHiddenExtension = true
                    let previewItem = PreviewItem()
                    previewItem.previewItemURL = previewURL
                    self.previewItems.append(previewItem)
                    DispatchQueue.main.async {
                        UIApplication.shared.isNetworkActivityIndicatorVisible = false
                        self.previewController.delegate = self
                        self.previewController.dataSource = self
                        self.previewController.currentPreviewItemIndex = 0
                        self.present(self.previewController, animated: true)
                     }
                } catch {
                    print(error)
                    return
                }
            }.resume()
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        }
        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { previewItems[index] }
        func presentAlertController(with message: String) {
             // present your alert controller from the main thread
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
                alert.addAction(.init(title: "OK", style: .default))
                self.present(alert, animated: true)
            }
        }
    }
    

    ExtensionsURL.swift

    extension URL {
        var hasHiddenExtension: Bool {
            get { (try? resourceValues(forKeys: [.hasHiddenExtensionKey]))?.hasHiddenExtension == true }
            set {
                var resourceValues = URLResourceValues()
                resourceValues.hasHiddenExtension = newValue
                try? setResourceValues(resourceValues)
            }
        }
    }
    

    PreviewItem.swift

    import QuickLook
    class PreviewItem: NSObject, QLPreviewItem {
        var previewItemURL: URL?
    }
    

提交回复
热议问题