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 to have the need to display web content within your apps. The iOS SDK offers three options for developers to achieve this:

  • Mobile Safari - The iOS SDK provides APIs that allow you to open a specific URL in the built-in Mobile Safari browser. In this scenario, your users temporarily leave the application and switch to Safari to view the web content.
  • WKWebView - This view enables developers to embed web content directly within their apps. Think of WKWebView as a simplified version of Safari specifically designed for app integration. It is responsible for loading URL requests and displaying web content. WKWebView utilizes the Nitro JavaScript engine and offers additional features. If your goal is to display a specific web page, WKWebView is the recommended option for this use case.
  • SFSafariViewController - While WKWebView allows you to embed web content, it does not provide a complete web browsing experience out of the box. For example, WKWebView lacks the Back/Forward buttons that allow users to navigate through browsing history. To offer such functionality, developers would need to build a custom web browser using WKWebView. However, with the introduction of SFSafariViewController, developers no longer need to create their own web browser from scratch. By utilizing SFSafariViewController, users can enjoy all the features of Mobile Safari without leaving your app. It provides a seamless browsing experience within your app, including navigation controls.
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 ""