How to Use SafariViewController in Swift
Published in
3 min readJun 7, 2019
- Mobile apps and viewing content on the web are easy now a days. For years, iOS developers have been charged with either creating their own web viewing experience inside their app or handing off the URL to Safari. Both of these approaches bring disadvantages that were previously unavoidable.
- That’s all changed with iOS 9 and the introduction of the
SFSafariViewController
class. With it, you can now provide a full web viewing experience inside your app without having to spend important development time providing it. SFSafariViewController
embeds all of Safari inside your app using an opaque view controller.- You can’t style it, you can’t interact with it, and you certainly can’t pull any private data out of it, and as a result
SFSafariViewController
can take advantage of the user's secure web data in ways thatUIWebView
andWKWebView
never could. - What’s more, Apple builds powerful features right into
SFSafariViewController
, so you get things like content blocking free of charge – and users get consistent features, consistent UI, and consistent security. SFSafariViewController
is not part of UIKit, so you need to import a new framework to use it. (import SafariServices)
Let’s dive into Xcode by creating new project.
- Import neccesary image files to do designing in storyboard.
1) Storyboard
- In above storyboard designing, I have created a simple design which shows imageview and button to watch video.
- I have renamed ViewController.Swift to HomeViewController and connected to main storyboard viewcontroller.
2) HomeViewController.Swift
- In HomeViewController File, we are going to import SafariServices below import UIKit framework to access safariViewController actions.
- We are going to extend SFSafariViewControllerDelegate to use SafariViewController functions.
var videoLink: String = “https://developer.apple.com/videos/play/wwdc2019/706/"
@IBAction func openVideoLinkInSafari(_ sender: Any) {
showSafariVC(for: videoLink)
}
func showSafariVC(for url: String) {
guard let url = URL(string: url) else {
return
}
let safariVC = SFSafariViewController(url: url)
safariVC.delegate = self
present(safariVC, animated: true)
}
- When watch video button is tapped we send the videoLink to SFSafariViewController.
- We are going to present safariViewController on HomeViewController.
- After all work is completed ,tapping done will get back to HomeViewController.
- By using SafariViewController, we can load any external url in App.