I'm following this tutorial on how to create a WebView in SwiftUI except that i'm making it for a macOS app and not IOS.
I switched UIViewRepresentable to NSViewRepresentable and i get this error: Type 'SwiftUIWebView' does not conform to protocol'NSViewRepresentable'
import SwiftUI
import WebKit
import AppKit
struct SwiftUIWebView: NSViewRepresentable {
let url: URL?
func makeUIView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
let webView = WKWebView(frame: .zero, configuration: config)
}
func updateUIView(_ uiView: WKWebView, context: Context) {
guard let myURL = url else {
return
}
let request = URLRequest(url: myURL)
uiView.load(request)
}
}
You also need to use makeNSView
protocol delegate instead of makeUIView
.
struct SwiftUIWebView: NSViewRepresentable {
let url: URL?
func makeNSView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
let webView = WKWebView(frame: .zero, configuration: config)
return webView
}
func updateNSView(_ nsView: WKWebView, context: Context) {
guard let myURL = url else {
return
}
let request = URLRequest(url: myURL)
nsView.load(request)
}
}
Please have a look at the documentation
The methods are makeNSView
and updateNSView
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.