这是我在一个项目(iOS 10,Swift 3)中加载本地文件时使用的简化版本.根据Raghuram和Fox5150在 comments 中的要求,在iOS 10.3.1和iPhone 7+上再次测试后,我只有updated my code (7.5.2017)个.
我刚刚创建了一个全新的项目,这是文件夹 struct :
Update 19.04.2018:增加了一个新功能来下载.使用HTML、CSS、JS文件压缩,在/Documents/(Alamofire+zip)中解压缩,然后将这些文件加载到webView中.你也可以在GitHub sample project中找到它.再一次,请随意使用fork&;明星!:)
Update 08.02.2018:最终添加了一个GitHub sample project,其中还包括一个本地JavaScript文件.请随意使用fork&;明星!:)
带有webView的版本1.loadFileURL()
视图控制器.敏捷的
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的版本2.loadHTMLString()
视图控制器.敏捷的
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 {
// catch error
}
webView.navigationDelegate = self
view = webView
}
}
Gotchas to look out for:
- Make sure that your local html/js/css files are in Project -> Target -> Build Phases -> Copy Bundle Resources
- 确保你的html文件不引用相对路径,例如
css/styles.css
,因为iOS会使你的文件 struct 和样式扁平化.css将与索引处于同一级别.所以写<link rel="stylesheet" type="text/css" href="styles.css">
吧
Given the 2 versions and the gotchas here are my html/css files from the project:
网络/索引.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>
css/web样式.css
#webkit-h1 {
font-size: 80px;
color: lightblue;
}
如果有人想要一个GitHub示例项目,请在 comments 部分告诉我,我会上传它.