2017-11-06 3 views

Antwort

5

Sie können nicht. QuickLook funktioniert nur für lokale Ressourcendateien. Sie müssten die Daten zuerst asynchron herunterladen, dann im Dokumentverzeichnis oder in einem temporären Ordner speichern und den QLPreviewController nach Abschluss des Vorgangs aus dem Hauptthread präsentieren:

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