Skip to content

Swift WKWebView 加载网页或本地文件

Published: at 10:02 AMSuggest Changes

Swift 入门

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

WKWebView 加载网页或者本地文件

最有帮助的是这篇文章

其他参考文章

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

代码

webviewApp.swift

import SwiftUI

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

ContentView.swift

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()
    }
}


Previous Post
JavaScript 获取视频和图片加载状态
Next Post
TensorFlow 错误:texture size [0x0] is invalid