How to preload content in SFSafariViewController

SFSafariViewController offers iOS developers to load web page inside their app’s. Though there is another control called WKWebView that does the same thing, but offers more customization’s. One should use WKWebView if your app implements customize behavior (UI or behind the scene thing). If you want to show only a webpage for example privacy policy or terms and condition, that offers only static text.

In this post we are going to learn how to preload content in SFSafariViewController. If you noticed that when we open a webpage in SFSafariViewController, it takes few seconds to load. Example of such pages are the ones those load resource-intensive content. So if you want to overcome this user experience, and not want to let your app user wait for content to load then SFSafariViewController offers new method called “prewarmConnections“.

PrewarmConnections is class method that accepts array of URL’s and return a token for further use. One can invalidate this token to stop preloading of url’s. So in order to preload contents you can use below code.

let urls = [URL(string: "https://iostutorialjunction.com")!]
let token = SFSafariViewController.prewarmConnections(to: urls)

Note:- prewarmConnections is only available iOS 15.0 and onward.

Tip: One can write “prewarmConnections” method on app launch. So that by the time user open that web page screen, app finish pre loading in background.

Try and run your app, and you can see the difference in loading speed of the webpage. Hope it helps.