Safari View Controller 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. In iOS 9 the Safari View Controller can be used to provide a full web experience inside of your application. In this tutorial we will display a webpage inside a Safari View Controller. This tutorial is made in Xcode 7 for iOS 9.

Open Xcode and create a new Single View Application. For product name, use IO9SafariViewControllerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. Drag a Button from the Object Library to the center of 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 and 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: AnyObject)
    let safariVC = SFSafariViewController(URL: NSURL(string: "")!)
    self.presentViewController(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.dismissViewControllerAnimated(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 IO9SafariViewControllerTutorial at the ioscreator repository on Github.