Chapter 23
Getting Started with WKWebView and SFSafariViewController
I've got a theory that if you give 100% all of the time, somehow things will work out in the end.
- Larry Bird
It is very common you need to display web content in your apps. From iOS 9 and onward, it provides three options for developers to show web content:
- Mobile Safari - the iOS SDK provides APIs for you to open a specific URL in the built-in Mobile Safari browser. In this case, your users temporarily leave the application and switch to Safari.
- WKWebView - Before the release of iOS 9, this is the most convenient way to embed web content in your app. You can think of
UIWebView
as a stripped-down version of Safari. It is responsible to load a URL request and display the web content.WKWebView
, introduced in iOS 8, is an improved version ofUIWebView
. It has the benefit of the Nitro JavaScript engine and offers more features. If you just need to display a specific web page,WKWebView
is the best option for this scenario. - SFSafariViewController - this is a new controller introduced in iOS 9. While
WKWebView
allows you to embed web content in your apps, you have to build a custom web view to offer a complete web browsing experience. For example,WKWebView
doesn't come with the Back/Forward button that lets users navigate back and forth the browsing history. In order to provide the feature, you have to develop a custom web browser usingWKWebView
. In iOS 9, Apple introducedSFSafariViewController
to save developers from creating our own web browser. By usingSFSafariViewController
, your users can enjoy all the features of Mobile Safari without leaving your apps.
In this chapter, I will walk you through all the options and show you how to use them to display web content. We will not talk about UIWebView
as it is deprecated and no longer available from iOS 13.
We have created About.storyboard
in the previous chapter. However, we didn't provide any implementation yet. Take a look at figure 23-1. That is the About screen we're going to create, and here are how each of the rows works:
- Rate us on App Store - when selected, we will load a specific iTunes link in Mobile Safari. Users will leave the current app and switch to the App Store.
- Tell us your feedback - when selected, we will load a Contact Us web page using
WKWebView
. - Twitter / Facebook / Pinterest - Each of these items has its own link for the corresponding social profile. We will use
SFSafariViewController
to load these links.
Sounds interesting, right? Let's get started.
To access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.