Opening a URL through SFSafariViewController

If you are familiar with the iOS platform you most likely have seen an app that opens a link in Safari in a way that allows you to go back to the app quickly.

It looks like this:

Simulator Screen Shot Dec 3, 2016, 10.37.07 PM.png

Notice that there is a “Done” button at the top left of Safari which takes you directly back to the view of your app.

This is useful when you are creating an app that needs to display a webpage quickly and allow the user to easily go back to your app after. It is also a lot faster than creating a new scene within our Storyboard and implementing a Web View in it which also still requires you to implement the functionality of loading the URL.

Safari Services & SFSafariViewController

To add this functionality to your app, you need to import the SafariServices library. This contains a class called SFSafariViewController which will display the webpage for us!

After importing SafariServices into your View Controller you can throw in the block of code below to open your URL.

Screen Shot 2016-12-03 at 10.41.31 PM.png

*The code above is explained below based on the commented numbers in the code

  1. We need to first create a new URL object from a string URL and unwrap the URL Optional
  2. Then create a new SFSafariViewController object and pass in that URL object. This method also takes a parameter entersReaderifAvailable which is a special webpage reading format that Safari supports.
  3. The last step is to present this new SFSafariViewController. Doing so will also load the site from the URL and allow the user to easily enter back into your core app!

That’s it!

SFSafariViewController is a really clean and easy way to present websites from your app without having to handle the web request and data display yourself!