How to use WebViews with navigation in Swift

Dec 17, 2019 · 3 min read

Web views are frequently used in iOS apps for high-performance web rendering. Apple makes it simple as they provide a great framework to use them: WebKit.

We are going to use WKWebView for a basic web rendering and see how we can handle navigation between the pages of the website.

Rendering a website

Here is the code to render a website like a navigator would have done:

First, we create a class property that will contain our web view (don’t forget to import WebKit)

Then, in the loadView method, we create a web view with the default configuration and a frame.

You can see that we also set the navigationDelegate of the web view to self. so we can later handle the navigation in our web views. The controller needs to conform to the navigationDelegate protocol but all the methods are optional so we can keep it like that for the moment.

We can now set our view to be the web view!

When the web view is set up, you need to load a URL.

In viewDidLoad, we use the load method of our web view to render a website and that’s it! You can now see the website and navigate through its pages.

Handling navigation

First of all, if you want to reproduce my code, the view controller that contains the web view needs to be embedded in a Navigation Controller. In real-life projects, you can do the same on whatever buttons you want.

Here is the code:

First, we are just adding the right buttons to our navigation bar.

One is to go to back in the webpage history (if it’s possible) and the other one is to go forward in the webpage history (again, if it’s possible).

Then, if the web view is loading we add an activity indicator to tell users that the page is loading.

When the loading is over, the delegate method webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) is called.

In this method, we set our navigation bar title to be the title of the webpage and we replace the activity indicator with the refresh button.


Congratulations, we create a navigator using web views!

Web views are very powerful if you want to open a link in your app but still keep the user in the app.

That’s the code I use in my projects with clients when I need to create web views. Feel free to use and modify it depending on your needs!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade