Geek Culture
Published in

Geek Culture

How to use WebView in SwiftUI and Detect the URL?

In this blog you will learn about how to use the WebView into the SwiftUI by using the UIViewRepresentable and also you will learn how to detect which url is open into the WebView.

Create the brand new SwiftUI project and then follow along the blog.

Create showWebView @State property inside the ContentView which will be used for presenting the fullScreenCover. Also create a sample button which will toggle the showWebView property. Then use the fullScreenCover for opening the WebView inside the application.

Now, First import the WebKit.

After that create a new struct and inhered the struct with UIViewRepresentable protocol and implement two necessary methods

makeUIView(context: Context) -> WKWebView and

updateUIView(_ webView: WKWebView, context: Context)

makeUIView method is used for create that view and updateUIView method is used for updating the view.

Also create two properties inside that struct. url is for getting the URL from parent view and showWebView for binding the fullScreenCover value to that WebView for dismissing the fullScreenCover.

After that use the WebView inside the fullScreenCover and pass the URL and bind the showWebView.

After that run the code and click on the “Open WebView” button and you will see website will be open inside your app.

For detecting which url is opened inside that WebView we need to implement WebKit WKNavigationDelegate.

For that we need to create a class inside the WebView struct.

Create a class WebViewCoordinator and inhered this with NSObject and WKNavigationDelegate. Create a property of WebView which we created earlier. Initialise that inside the class using init.

Now implement the following WKNavigationDelegate method to detect which URL is opened currently inside the WebView.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

Inside that method by writing the navigationAction.request.url?.absoluteString, We can check which URL is opened inside the WebView.

That method will called every time when URL change inside the WebView.

Inside that method, get the URL which is opened inside the WebView and then comparing it with the urlToMatch if both urls matches then dismissing the WebView.

Use the WebViewCoordinator class by implementing another function makeCoordinator( ).

Finally give the context of that coordinator to the WKWebView and run the code. When you open another link inside that WebView method inside that WebViewCoordinator will runs and detect the URL.

FULL CODE:

Hope you enjoyed this blog. Thanks for reading this.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store