swift-wkwebview單頁(yè)App下載zip文件解壓展示html

前言

實(shí)現(xiàn)功能,單頁(yè)app下載zip壓縮包,其中包含html,css,js等文件,加載html展示.此次沒(méi)做下載功能而是把zip壓縮包放在mainbundle里面

移動(dòng)zip包到指定位置

因?yàn)?code>webView.loadFileURL(URL, allowingReadAccessTo: URL)方法必須ios9以上使用,而使用webView.load(URLRequest)方法,根據(jù)WKWebView使用遇到的坑--加載本地html
要把文件移動(dòng)到/temp/www/下面,所以我直接把文件放在/temp/www/下

let filePath = Bundle.main.path(forResource: "dist", ofType: "zip")
let fileURL = URL.init(fileURLWithPath: filePath!)
do{
      fileURL = try fileURLForBuggyWKWebView8(fileURL: fileURL)
      print(fileURL);
  }catch  let error as Error{
      print("Error:"+error.localizedDescription)
  }
  

以下方法是在WKWebView使用遇到的坑--加載本地html
基礎(chǔ)上根據(jù)swift4.0的變化而修改的

func fileURLForBuggyWKWebView8(fileURL: URL) throws -> URL {
   // Some safety checks
   let error:NSError? = nil;
   let reachable = try! fileURL.checkResourceIsReachable()
   if (!fileURL.isFileURL || !reachable) {
       throw error ?? NSError(
           domain: "BuggyWKWebViewDomain",
           code: 1001,
           userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("URL must be a file URL.", comment:"")])
   }
   // Create "/temp/www" directory
   let fm = FileManager.default
   let tmpDirURL = URL.init(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("www")
   try! fm.createDirectory(at: tmpDirURL, withIntermediateDirectories: true, attributes: nil)
   let dstURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponent)
   let _ = try? fm.removeItem(at: dstURL)
   try! fm.copyItem(at: fileURL, to: dstURL)
   return dstURL
}

解壓文件--SSZipArchive

pod安裝SSZipArchive
1.在Podfile添加pod SSZipArchive,然后cd到項(xiàng)目路徑下,輸入pod install回車(chē)等待安裝完畢
2.添加libz庫(kù),如下圖

QQ20180328-164541@2x.png

3.頁(yè)面import SSZipArchive,添加如下代碼

let tmpDirURL =  NSTemporaryDirectory()+("www") //dist.zip所在位置      
let done = SSZipArchive.unzipFile(atPath: tmpDirURL+"/dist.zip", toDestination: tmpDirURL+"/")//解壓,兩個(gè)參數(shù)一個(gè)是文件的路徑,一個(gè)是解壓后的位置
if done {
  print("解壓成功")
}else{
  print("解壓失敗")
}

加載html

直接使用webView.load(URLRequest)加載就可以了

webView.load(URLRequest.init(url: URL.init(fileURLWithPath: tmpDirURL+"/dist/index.html")))
最后,可能寫(xiě)的有點(diǎn)亂,尷尬??
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容