WKWebview不呈现.doc文件,而是呈现pdf / png / jpeg?

时间:2018-11-20 11:58:52

标签: ios swift file

当尝试加载其他文件类型(例如PDF,PNG,JPEG)时,它可以完美运行。 还尝试将.doc数据加载到UIWebview中,它也可以正常工作。我正在使用JSON编码从Base64从服务器获取数据。

let webview = WKWebView() 
webview.load(data, mimeType: "application/msword", characterEncodingName: "UTF-8", baseURL: NSURL() as URL)

有人也遇到过这个问题吗? 该文件不应保存在本地。 这是条件。

1 个答案:

答案 0 :(得分:1)

您需要为此使用Quicklook,这是iOS的本机功能:-

import Foundation
import UIKit
import QuickLook

class ClassQuickLookFilePreviewHandler {

static let shared = ClassQuickLookFilePreviewHandler()

var url: URL?
var tempURL: URL?

func previewFile(vc: UIViewController, url: URL, fileName: String) {
    let previewController = QLPreviewController()
    self.url = url
    previewController.dataSource = self
    previewController.view.tintColor = UIColor(hexString: "#ff3366")
    tempURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName)

    previewController.currentPreviewItemIndex = 0
    URLSession.shared.dataTask(with: url) { data, _, 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))
                vc.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
                vc.present(previewController, animated: true)

            }
        } catch {
            print(error)
            return
        }

        }.resume()
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}

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

func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    return tempURL! as QLPreviewItem
}
}

用法:-

ClassQuickLookFilePreviewHandler.shared.previewFile(vc: self, url: URL(string: ?*documentURL)!, fileName: ?*documentFileName)

希望它会有所帮助:)

相关问题