前言
實(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")))