How to open a URL in Safari in Swift

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 03/09/2023 at 08:31
Last Updated on 03/09/2023 at 09:27
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.

Subscribe

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.

How to create a SwiftLint enabled Swift Xcode Project

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
View Repository

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.

How to make a custom button in Swift

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe