I am loading a local html file with this inside <script>
window.webkit.messageHandlers.MyHandler.postMessage("hello");
What changes do i need on my swift file to handle setup this handler?
my current swift file :
struct WebView: UIViewRepresentable {
var url: URL
...
func makeUIView(context: Context) -> WKWebView {
// do configuration here
let view = WKWebView()
view.navigationDelegate = context.coordinator
view.load(URLRequest(url: url))
return view
}
...
Thanks.
Tried this:
func makeUIView(context: Context) -> WKWebView {
let userController = WKUserContentController()
userController.add(self, name: "MyHandler")
let configuration = WKWebViewConfiguration()
configuration.userContentController = userController
return WKWebView(frame: frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 500, maxHeight: .infinity) as! CGRect, configuration: configuration)
but i'm getting error on self: Argument type 'WebView' does not conform to expected type 'WKScriptMessageHandler'
struct WebView: UIViewRepresentable { ... }, and most of the answers (I've found, so far) start withclass ViewController: UIViewController. It's really tripping me up (sorry, i am new with swift). I don't know how to transform the swiftui answers to just UIKit.add(_:name:)onWKUserContentControllerrequires thatselfconforms toWKScriptMessageHandler, because you are using it as argument. You could try to conform yourWebViewto the required protocol.