iOS 9 Swift Programming Cookbook (2015)
Chapter 3. The User Interface
3.6 Showing Web Content in Safari View Controller
Problem
You want to take advantage such awesome Safari functionalities as Reader Mode in your own apps.
Solution
Use the SFSafariViewController class in the SafariServices.framework. This view controller can easily be initialized with a URL and then displayed on the screen.
Discussion
Let’s go ahead and build the UI. For this recipe, I am aiming for a UI like Figure 3-19.
Figure 3-19. Create a UI that looks similar to this in your own storyboard
Then hook up the text field and button to your code. Once the button is tapped, the code that runs is:
@IBAction func openInSafari() {
guard let t = textField.text where t.characters.count > 0,
let u = NSURL(string: t) else{
//the url is missing, you can further code this method if you want
return
}
let controller = SFSafariViewController(URL: u,
entersReaderIfAvailable: true)
controller.delegate = self
presentViewController(controller, animated: true, completion: nil)
}
Now make your view controller conform to the SFSafariViewControllerDelegate protocol. Program the safariViewControllerDidFinish(_:) method to ensure that, when the user closes the Safari view controller, the view disappears:
func safariViewControllerDidFinish(controller: SFSafariViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
In the initializer of the safari controller, I also specified that I would like to take advantage of the reader mode if it is available.
See Also