I've got a SwiftUI app that uses two separate web views to display html pages stored in a CoreData database. When the user clicks on a link in one web view, the linked file is shown in the second web view. To make this happen I'm using the following:
struct LibCompWebView: UIViewRepresentable {
let request: URLRequest
func makeCoordinator() -> Coordinator {
.init(self)
}
func makeUIView(context:Context) -> WKWebView {
let webView = WKWebView()
webView.navigationDelegate = context.coordinator
return webView
}
func updateUIView(_ webView: WKWebView, context: Context) {
webView.load(request)
}
class Coordinator: NSObject, WKNavigationDelegate {
var webView: LibCompWebView
init(_ webView:LibCompWebView) {
self.webView = webView
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
navigateLibCompTo(theURL:navigationAction.request.url!)
decisionHandler(.cancel)
} else {
print("not a user click")
decisionHandler(.allow)
}
}
}
}
In that NavigationDelegate is a call to a function called navigateLibCompTo, which passes the URL that the user clicked on to a function that is then supposed to look up the appropriate stuff from my coredata entity and load it into the appropriate web view.
I'm sharing my CoreData stuff as a StateObject accessed through an @environmentobject. The problem is that my navigateLibComp function is outside of my view hierarchy, so I have no way to access the CoreData stuff.
I'm completely stumped!