Swift Open Link in Safari Swift Open Link in Safari swift swift

Swift Open Link in Safari


It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:).

Swift 4 + Swift 5 (iOS 10 and above)

guard let url = URL(string: "https://stackoverflow.com") else { return }UIApplication.shared.open(url)

Swift 3 (iOS 9 and below)

guard let url = URL(string: "https://stackoverflow.com") else { return }UIApplication.shared.openURL(url)

Swift 2.2

guard let url = URL(string: "https://stackoverflow.com") else { return }UIApplication.sharedApplication().openURL(url)    


New with iOS 9 and higher you can present the user with a SFSafariViewController (see documentation here). Basically you get all the benefits of sending the user to Safari without making them leave your app. To use the new SFSafariViewController just:

import SafariServices

and somewhere in an event handler present the user with the safari view controller like this:

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

The safari view will look something like this:

enter image description here


UPDATED for Swift 4: (credit to Marco Weber)

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {     UIApplication.shared.openURL(requestUrl as URL) }

OR go with more of swift style using guard:

guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {    return}UIApplication.shared.openURL(requestUrl as URL) 

Swift 3:

You can check NSURL as optional implicitly by:

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {     UIApplication.sharedApplication().openURL(requestUrl)}