直接在应用程序中呈现下载文件的预览

Present preview of downloaded file directly in app

我的应用程序有文件下载选项,它使用 alamofire 下载方法下载文件。下载完成后,我需要在不将文件保存到 internal/cloud 存储的情况下显示文件的预览。我怎样才能实现这个类似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)
        })
}

要显示文件预览,请使用 Apple 的 QuickLook 框架,该框架可让您嵌入大量文件类型的预览,包括 iWork 文档、Microsoft Office 文档、PDF、图像等,所有这些都无需写了很多代码。

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

参考:

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

  2. https://github.com/gargsStack/QLPreviewDemo

  3. https://www.appcoda.com/quick-look-framework/

代码:

class ViewController: UIViewController {
    var previewItem = URL!

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

        Alamofire.download(fileUrl, to: destination)
        .response(completionHandler: { (downloadResponse) in

            let previewController = QLPreviewController()
            previewController.dataSource = self
            self.previewItem = downloadResponse.destinationURL
            self.present(previewController, animated: true, completion: nil)
        })
    }
}

extension ViewController: QLPreviewControllerDataSource {
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
       return self.previewItem as QLPreviewItem
    }
}

这是一个使用 Alamofire 的解决方案。有人可能会帮忙。

步骤:

  • Alamofire 有优秀的员工直接下载,也save/write 你的文件存入光盘。

  • Return下载文件的保存路径

  • 使用UIDocumentInteractionController传递文件路径

  • 然后呈现这个观点

     import Alamofire
    
         extension UIViewController : UIDocumentInteractionControllerDelegate{
    
    
         func downloadFileForPreview(fileName: String, fileExtension: String, filePath: String )  {
    
    
             let destination: DownloadRequest.DownloadFileDestination = { _, _ in
                 let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    
                 let fileWithExtension = "file.\(fileExtension)"
    
                 let fileURL = documentsURL.appendingPathComponent(fileWithExtension)
    
                 return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
             }
             //UtilitySwift.showUniversalLoadingView(true)
             Alamofire.download(filePath, to: destination).response {  response in
                 debugPrint(response)
             //UtilitySwift.showUniversalLoadingView(false)
    
                 if response.error == nil, let storeFilePath = response.destinationURL?.path {
                     //let image = UIImage(contentsOfFile: imagePath)
                     self.previewDocument(withFilePath: response.destinationURL)
                     print(storeFilePath)
    
                 }
    
                 else{
                     UtilitySwift.showErrorMessage(message: response.error?.localizedDescription ?? "Error occured when downloading" )
                     print(response.error?.localizedDescription ?? "")
                 }
    
             }
         }
    
    
         //  Converted to Swift 5.1 by Swiftify v5.1.29672 - https://objectivec2swift.com/
         func previewDocument(withFilePath filePath: URL?) {
    
             var documentInteractionController: UIDocumentInteractionController?
    
             if filePath != nil {
                 // Initialize Document Interaction Controller
                 if let filePath = filePath {
                     documentInteractionController = UIDocumentInteractionController(url: filePath)
                 }
    
                 // Configure Document Interaction Controller
                 documentInteractionController?.delegate = self as UIDocumentInteractionControllerDelegate
    
                 //if not possible to open
                 if !documentInteractionController!.presentPreview(animated: true) {
                     documentInteractionController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true)
                 }
    
             } else {
                 // error
                 print("file preview error")
             }
         }
         //UIDocumentInteractionControllerDelegate
         public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
             self
         }
    
         }
    

来自任何 UIViewController

的呼叫
self.downloadFileForPreview(fileName: "file", fileExtension: fileExt ?? "", filePath: REPLACE_WITH_DOWNLOAD_URL)