Chapter 22
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 WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView 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 using WKWebView. In iOS 9, Apple introduced SFSafariViewController to 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.
Figure 22-1. The About screen of the FoodPin app
Figure 22-1. The About screen of the FoodPin app

In this chapter, I will walk you through all the options and show you how to use them to display web content. For both WKWebView and SFSafariViewController, we will need to make use of UIViewRepresentable and 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.

results matching ""

    No results matching ""