直接在应用程序中显示下载文件的预览

Vai*_* KP 1 quicklook ios document-preview swift

我的应用程序有文件下载选项,可以使用 alamofire 下载方法下载文件。下载完成后,我需要显示文件的预览,而不将其保存到内部/云存储。我怎样才能实现这个类似whatsapp的功能,在下载文件后显示预览。

func downloadFile(fileUrl: URL) {
    let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)

    Alamofire.download(fileUrl, to: destination)
        .response(completionHandler: { (downloadResponse) in
            self.dic.url = downloadResponse.destinationURL
            self.dic.uti = downloadResponse.destinationURL!.uti
            let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
            self.dic.presentOpenInMenu(from: rect, in: self.view, animated: true)
        })
}
Run Code Online (Sandbox Code Playgroud)

Vai*_* KP 6

要呈现文件预览,请使用 Apple\xe2\x80\x99sQuickLook框架,该框架允许您嵌入各种文件类型的预览,包括 iWork 文档、Microsoft Office 文档、PDF、图像等,而无需编写太多代码。

\n\n

首先,导入 QuickLook 框架,然后使您的视图控制器符合 QLPreviewControllerDataSource 协议。

\n\n

参考:

\n\n
    \n
  1. https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller

  2. \n
  3. https://github.com/gargsStack/QLPreviewDemo

  4. \n
  5. https://www.appcoda.com/quick-look-framework/

  6. \n
\n\n

代码:

\n\n
class ViewController: UIViewController {\n    var previewItem = URL!\n\n    func downloadFile(fileUrl: URL) {\n        let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)\n\n        Alamofire.download(fileUrl, to: destination)\n        .response(completionHandler: { (downloadResponse) in\n\n            let previewController = QLPreviewController()\n            previewController.dataSource = self\n            self.previewItem = downloadResponse.destinationURL\n            self.present(previewController, animated: true, completion: nil)\n        })\n    }\n}\n\nextension ViewController: QLPreviewControllerDataSource {\n    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {\n        return 1\n    }\n\n    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {\n       return self.previewItem as QLPreviewItem\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n