0

I'm trying create a WebView view in SwiftUI 2.0 Xcode 12.4 but it's so new I can't find good examples for answers and best practice. For the code below I get the following error.

Type 'SwiftUIWebView' does not conform to protocol 'UIViewRepresentable'

Also setting the config has changed and I can't enable .allowsContentJavaScript properly. Trying to add it to the "perfs" triggers an error complaining about not liking a Bool.

import SwiftUI
import WebKit

struct SwiftUIWebView: UIViewRepresentable {
    let url: URL?
    func makeUIView(context: Context) -> some WKWebView {
        let prefs = WKWebpagePreferences()
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences = prefs
        return WKWebView(frame: .zero, configuration: config)   //frame CGRect
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
        guard let myURL = url else { return }
        let request = URLRequest(url: myURL)
        uiView.load(request)
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
David
  • 171
  • 2
  • 11

1 Answers1

1

Remove some from this line:

func makeUIView(context: Context) -> some WKWebView {

some is a specific keyword used when dealing with generics and opaque types (see this link for more reading: What is the `some` keyword in Swift(UI)?). In this case, you don't need to generic-ize WKWebView, since you know exactly what it is.

You can set the prefs.allowsContentJavaScript property by doing this:

prefs.allowsContentJavaScript = true
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • Here is what worked in the end. Getting rid of the "some" and it rejected adding this to perfs so did this way and it works: ``` func makeUIView(context: Context) -> WKWebView { let config = WKWebViewConfiguration() config.defaultWebpagePreferences.allowsContentJavaScript = true return WKWebView(frame: .zero, configuration: config) //frame CGRect } ``` – David Jan 29 '21 at 22:48