tour the programming library language developer apple ios swift document

ios - library - the swift programming language pdf



Cómo mostrar documentos remotos usando QLPreviewController en swift (1)

Estoy usando QLPreviewController para obtener una vista previa de los documentos. Pero no sé cómo mostrar el documento almacenado en un servidor.


No puedes QuickLook solo funciona para archivos de recursos locales. Debería descargar los datos de forma asincrónica primero, guardarlos en el directorio de documentos o en una carpeta temporal y presentar el QLPreviewController desde el hilo principal cuando haya terminado:

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