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.
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
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
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
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
Run the app in XCode and press the button to confirm that the webpage opens in Safari.