Displaying Web Content 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. The iOS SKD 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 - This view allows developers to embed web content in your app. You can think of
WKWebViewas a stripped-down version of Safari. It is responsible to load a URL request and display the web content.
WKWebViewis the best option for this scenario.
- SFSafariViewController - this is a new controller introduced in iOS 9. While
WKWebViewallows 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,
WKWebViewdoesn'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 using
WKWebView. In iOS 9, Apple introduced
SFSafariViewControllerto save developers from creating our own web browser. By using
SFSafariViewController, 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. For both
SFSafariViewController, we will need to make use of
UIViewControllerRepresentable to integrate with these components because they are only available in UIKit.
To demonstrate how to show web content in SwiftUI, we will build the About tab to display three options:
- 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 / Instagram - 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.