这是我在我的项目中使用的加载本地文件的简化版(iOS 10,Swift 3)。如Raghuram和Fox5150在评论中所请求的,在iOS 10.3.1和iPhone 7+上测试后,我刚刚更新了我的代码(7.5.2017)。
我刚刚创建了一个全新的项目,这是文件夹结构:
更新于19.04.2018:添加了一个新功能,可以下载包含HTML、CSS、JS文件的.zip文件,将其解压缩到/Documents/(使用Alamofire + Zip),然后将这些文件加载到webView中。您也可以在
GitHub示例项目中找到它。同样,随意fork & star! :)
更新于2018年08月02日:最终添加了一个GitHub示例项目,其中包含一个本地的JavaScript文件。欢迎fork和star!:)
使用webView.loadFileURL()的第一版
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView()
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
webView.navigationDelegate = self
view = webView
}
}
使用webView.loadHTMLString()的第二个版本
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView()
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlString as String, baseURL: baseUrl)
} catch {
}
webView.navigationDelegate = self
view = webView
}
}
需要注意的问题:
- 确保您的本地 html/js/css 文件在项目 -> 目标 -> 构建阶段 -> 复制捆绑资源中
- 确保您的 html 文件不引用相对路径,例如
css/styles.css
,因为 iOS 会压缩您的文件结构,并将 styles.css 放在与 index.html 同一级别,所以请改写为 <link rel="stylesheet" type="text/css" href="styles.css">
鉴于这两个版本和注意事项,以下是我的项目中的 html/css 文件:
web/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Offline WebKit</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1 id="webkit-h1">Offline WebKit!</h1>
</body>
</html>
web/css/styles.css
#webkit-h1 {
font-size: 80px;
color: lightblue;
}
如果有人需要 GitHub 的示例项目,请在评论区告诉我,我会上传它。
func loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL: URL) -> WKNavigation?
[https://developer.apple.com/reference/webkit/wkwebview/1414973-loadfileurl] - DocForNoc