我正在使用QLPreviewController预览文档。但是我不知道如何显示存储在服务器上的文档。
最佳答案
你不能QuickLook仅适用于本地资源文件。您需要首先异步下载数据,将其保存到文档目录或临时文件夹中,并在完成后从主线程显示QLPreviewController:
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
let preview = QLPreviewController()
let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("quicklook.pdf")
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return tempURL as QLPreviewItem
}
override func viewDidLoad() {
super.viewDidLoad()
preview.dataSource = self
preview.currentPreviewItemIndex = 0
let url = URL(string:"https://images.apple.com/environment/pdf/Apple_Environmental_Responsibility_Report_2017.pdf")!
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 and update the UI from the main thread
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let alert = UIAlertController(title: "Alert", message: error?.localizedDescription ?? "Failed to download the pdf!!!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
return
}
// write the downloaded data to a temporary folder or to the document directory if you want to keep the pdf for later usage
do {
try data.write(to: self.tempURL, options: .atomic) // atomic option overwrites it if needed
// you neeed to check if the downloaded data is a valid pdf
// and present your controller from the main thread
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if self.tempURL.typeIdentifier == "com.adobe.pdf" {
self.present(self.preview, animated: true)
} else {
print("the data downloaded it is not a valid pdf file")
}
}
} catch {
print(error)
return
}
}.resume()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
extension URL {
var typeIdentifier: String? {
return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
}
}
关于ios - 如何使用QLPreviewController快速显示远程文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387808/