出現問題情況是:將uiwebview換成wkwebview之后,之前將webview上那些圖片放回本地下載后緩存的圖片沒辦法在webview上找到,最后排查出原因是,wkwebview需要將圖片和網頁文件放在同個路徑下。
具體實現方法如下(獲取圖片緩存的路徑,將本地html和css文件復制到該路徑下):
css復制到圖片路徑:
let baseDir = ImageCacheTool.imageBasePath()!//本地圖片緩存路徑
? ? ? ? ? ? if !FileManager.default.fileExists(atPath: baseDir) {
? ? ? ? ? ? ? ? try? FileManager.default.createDirectory(atPath: baseDir, withIntermediateDirectories: true, attributes: nil)
? ? ? ? ? ? }
let srcPath = Bundle.main.path(forResource: "webview", ofType: "css")
? ? ? ? if !FileManager.default.fileExists(atPath: desPath) {
? ? ? ? ? ? try? FileManager.default.copyItem(atPath: srcPath ?? "", toPath: baseDir +?"/webview.css")
? ? ? ? }
html復制到圖片路徑
?let htmlPath = ImageCacheTool.imageBasePath() + "/index.html"
? ? ? ? try? html.write(toFile: htmlPath, atomically: true, encoding: .utf8)
? ? ? ? webView.loadFileURL(URL(fileURLWithPath: htmlPath), allowingReadAccessTo: URL(fileURLWithPath: ImageCacheTool.imageBasePath()))
?