BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

How to open web links in Safari

Paul Hudson    @twostraws   

Updated for Xcode 14.1

SwiftUI gives us a dedicated Link view that looks like a button but opens a URL in Safari when pressed. It’s easy enough to use – just give it a title for the button, plus a destination URL to show, like this:

Link("Learn SwiftUI", destination: URL(string: "https://www.hackingwithswift.com/quick-start/swiftui")!)

Download this as an Xcode project

As it’s just a text link, you can customize it with a font, color, and more:

Link("Visit Apple", destination: URL(string: "https://www.apple.com")!)
    .font(.title)
    .foregroundColor(.red)

Download this as an Xcode project

The words “Visit Apple” in red.

And if you’d rather create your own view rather than just use text, you can do that too:

Link(destination: URL(string: "https://www.apple.com")!) {
    Image(systemName: "link.circle.fill")
        .font(.largeTitle)
}

Download this as an Xcode project

A link icon on a blue circle.

Alternatively, you can open a URL from code by using the openURL environment key, like this:

struct ContentView: View {
    @Environment(\.openURL) var openURL

    var body: some View {
        Button("Visit Apple") {
            openURL(URL(string: "https://www.apple.com")!)
        }
    }
}

Download this as an Xcode project

A “Visit Apple” link in blue.

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.