NEW: Master Swift design patterns with my latest book! >>

How to open a URL in Safari

Written by Paul Hudson    @twostraws

If you want the user to exit your app and show a website in Safari, it's just one line of code in Swift. I'll make it three here because I'll create the URL in the code too, then safely unwrap it:

if let url = URL(string: "https://www.hackingwithswift.com") {
    UIApplication.shared.open(url, options: [:])
}

It's worth adding that since iOS 9 you have the option of using SFSafariViewController inside your app, which recreates the entire Safari experience right inside your app. See Hacking with Swift project 32 for a tutorial on how to do this.

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Server-Side Swift now!

Take your Swift code to the server and become a full-stack developer with my latest book: Server-Side Swift!

Click here to visit the Hacking with Swift store >>