I have been hunting everywhere for a solution to my problem, and for some reason I am struggling to find any good resources on creating WebViews in SwiftUI and customizing / setting delegates for it. I am working with a 3rd party API that requires me to open a WebView, the user logs into something, and when that's done (signal comes via reaching a certain URL), the sheet should close. At the same time, if a certain click is taken, a new tab would open up, but my WebView is blocking that so no action occurs. These types of links should open in Safari.
I have defined a very simple WebView: UIViewRepresentable already:
struct WebView: UIViewRepresentable {
var url: URL
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}
And it is called as such (note this is an example):
Button {
showModal.toggle()
} label: {
Text("**Check ESPN**")
}
.sheet(isPresented: $showModal
, onDismiss: {}
, content: {
WebView(url: URL(string: "https://www.espn.com")!)
}
)
I have found this StackOverflow question that appears to have the delegate I need to open a link in Safari when it attempts to open a new tab. Open a WKWebview target="_blank" link in Safari
On top of this, I need a delegate to watch the URL and when the url contains "done", then the sheet should close.
Where in the world do I put that delegate definition? How do I assign it as a delegate for my struct WebView
? Do I need to call my WebView in a different way within my sheet once I add the delegate?