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:
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.
*The code above is explained below based on the commented numbers in the code
- We need to first create a new URL object from a string URL and unwrap the URL Optional
- 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.
- 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!