How to open a URL in Safari in Swift

Oscar de la Hera Gomez
Two flowers that represent Swift and XCode side by side. Beneath them sits the text "Open URL in Safari."

A step by step tutorial on opening a webpage in Safari from an iOS, iPadOS or MacOS app.

The following tutorial builds on our Open Source Swift starter project, which can be downloaded using the link below, and walks you through how to open up a URL in a native Safari browser when a user presses a custom button on an app using Swift.

We recommend downloading our Open Source project, checking out the main branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/open-url branch.

git clone git@github.com:delasign/swift-starter-project.git

Step One: Create the button

A screenshot of an iPhone 13 in portrait with the product of this tutorial. On the left sits a screenshot showing the button in its default state, this is essentially white with black text. To its right sits a screenshot of the button in its highlighted state, i.e. when its being pressed - which is reflected as a black background with white text.

Create the button that opens the URL.

For a tutorial on how to create a custom button in Swift, please consult the article linked below.

Step Two: Create the URL Constant

A screenshot of Xcode on the Constants.swift file, with a highlight on the URL that we declared as "kDelasignBlogURL" which points to our blog.

In the Constants.swift file under Models/Constants, add your url as a constant.

Please note that this is optional but recommended.

Step Three: Open the URL

A screenshot of Xcode showing the implementation of the code that we have offered below, which opens up a URL in Safari.

In CustomUIView+UI.swift, in the onRelease callback from the custom button - or in the location that your button action takes place - open up the URL using the code below.

Please replace YOUR_URL with the constant created in Step Two.

Step Four: Verify

The delasign blog website page, which was opened after pressing the button.

Run the app in XCode and press the button to confirm that the webpage opens in Safari.

Any Questions ?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details