SFSafariViewController example

October 9, 2015

SFSafariViewController example

We all have experienced this in one way or another - you have an embedded browser in some app, but you inevitably found yourself wanting to switch to Safari with 'View in Safari' button. Why? Simply because user experienced in native Safari is better due to local storage and cookies.

Yes, starting from iOS8 we can all enjoy Safari-like browsing speed in apps, thanks to WKWebView. The problem was though, that each app had its own browser interface, which resulted in inconsistent look and feel across the system.

But now these problems are gone, since Apple's release of SFSafariViewController.


First things first: import SafariServices:

#import <SafariServices/SafariServices.h>

Afterwards we are instantiating SFSafariViewController and adding it as a subview. We have two options doing so:

  1. Creating with only base URL
  2. Creating with bas URL as well as entering 'Reading Mode' in case it is available

NSString *sURL = @"http://google.com";
SFSafariViewController *safari = [[SFSafariViewController alloc] initWithURL:URL]; // 1.
SFSafariViewController *safari = [[SFSafariViewController alloc] initWithURL:URL entersReaderIfAvailable:YES]; // 2.
[self presentViewController:safari animated:YES completion:nil];

It is worth mentioning though, that SFSafariViewController allows us to pass into URL that doesn't use secured protocols, so the URL looks like regular http://. This URL, starting from iOS9, would not open in UIWebView nor in WKWebView. So, here you go, another advantage.


There is nothing cool happening in delegate protocol:

  • safariViewController:didCompleteInitialLoad:

This method is invoked when SFSafariViewController completes the loading of the URL that you pass to its initializer. The method is not invoked for any subsequent page loads in the same SFSafariViewController instance.

  • safariViewController:activityItemsForURL:title:

The view controller calls this method when the view is about to show an activity view controller. Your delegate can provide unique application-specific services (such as a social media service) to be included with the system-provided sharing services.

  • safariViewControllerDidFinish:

Your method should dismiss the view controller.

This sums it up, basically. Not too much to control here, but definitely a nice solution for apps that don't require custom browser but do want to keep user from switching from their app to Safari and forget from where they have came from in the first place.


comments powered by Disqus