0%

Swift WKWebView 加载网页或者本地文件

Swift 入门

和同事联调 Webview 的 H5 页面,自己简单学习了一下

WKWebView 加载网页或者本地文件

最有帮助的是这篇文章

其他参考文章

参考项目,下载下来直接跑

代码

webviewApp.swift

1
2
3
4
5
6
7
8
9
10
import SwiftUI

@main
struct webviewApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

ContentView.swift

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
46
47
48
49
50
import SwiftUI
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!

override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}

override func viewDidLoad() {
super.viewDidLoad()
// let myURL = URL(string:"https://www.apple.com")
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
webView.load(URLRequest(url: url))
}
}

struct WebView_UI: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> some UIViewController {
let vc = WebViewController()
return vc
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}

struct ContentView: View {
var body: some View {
ScrollView{
Text("Header").padding()
WebView_UI()
.frame(height: 200.0)
Text("WxWebView").padding()
WebView_UI()
.frame(height: 1200.0)
Text("Footer").padding()
}
.frame(height: 350)

}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}