一尘不染

如何使用QLPreviewController快速显示远程文档

swift

我正在使用QLPreviewController预览文档。但是我不知道如何显示存储在服务器上的文档。


阅读 380

收藏
2020-07-07

共1个答案

一尘不染

你不能
QuickLook仅适用于本地资源文件。您需要首先异步下载数据,将其保存到文档目录或临时文件夹中,并在完成后从主线程中显示QLPreviewController:

编辑/更新:

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

扩展URL.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?
}
2020-07-07