Safari View Controller iOS Tutorial

Prior to iOS 9 when the user needs to connect to a web page the URL is handed off to safari. forcing the user to exit out of your application. From iOS 9 and later the Safari View Controller can be used to provide a full web experience inside of your application. In this tutorial a webpage is displayed inside a Safari View Controller. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSSafariViewControllerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard. Drag a Button from the Object Library to the main View. Double-click the button to change the title to "Open Web Page". Select the "Resolve Auto Layout Issues" button on the bottom-right and choose "Add Missing Constraints".

The Storyboard will look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag from the Button in the Storyboard to the ViewController class of the ViewController.swift file to create the following Action.

At the top of the ViewController.swift file import the SafariServices framework.

import SafariServices

Implement the openURL(_:) Action method.

@IBAction func openURL(_ sender: Any) {
    // check if website exists
    guard let url = URL(string: "") else {

    let safariVC = SFSafariViewController(url: url)
    present(safariVC, animated: true, completion: nil)

To dismiss the Safari View Controller the View Controller needs to conform to the SFSafariViewControllerDelegate. Change the class declaration to

class ViewController: UIViewController, SFSafariViewControllerDelegate

Add the following delegate method

func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    controller.dismiss(animated: true, completion: nil)

Finally add the following line to the openURL Action method

safariVC.delegate = self

Build an Run the Project and click on the button to open the website. The Safari View Controller is displayed containing the Apple Web Site. Pressing the Done button will dismiss the Safari View Controller.

You can download the source code of the IOSSafariViewControllerTutorial at the ioscreator repository on Github.