有个小需求,做个简单的 IOS APP,其实就是一个WebView,并且优先载入指定网址,如果载入失败就加载本地静态文件。
第一次玩,利用Google 还是顺利完成,记一下结果,下面是官方的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
}
在此基础上添加事件的响应,这里WKNavigationDelegate
与 WKUIDelegate
区别,前者主要处理一些跳转、加载处理操作,后者主要处理JS脚本,确认框,警告框等,为了监听页面的载入情况,使用WKNavigationDelegate
。全部代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 载入空白页
webView.loadHTMLString("<html><body><p>blank</p></body></html>", baseURL: nil)
let myURL = URL(string:"https://www.google.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
//web view start loading
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Strat loading")
}
//web view finish loading
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("finish loading")
}
//handle error
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "Website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}
静态文件目录结构:
1
2
3
4
5
6
Website/
├── app.js
├── clipboard.min.js
├── index.html
├── styles.css
└── tachyons.min.css
参考
本文网址: https://pylist.com/topic/177.html 转摘请注明来源