Swift Open Link in Safari in iOS Swift


In Swift, there are two ways to open a link. One approach is to use the UIApplication class to open a link in the Safari browser. Another approach is using the SafariServices framework in iOS. Let's see some examples of how to open a link based on these approaches.

Approach 1: Using the UIApplication class

  • Step 1 − Create a URL object for the link that you want to open. You can do this using the URL(string:) initializer.

  • Step 2 − Create an instance of the UIApplication class. This class is responsible for managing the behavior of your app, including opening URLs.

  • Step 3 − Use the open(_:options:completionHandler:) method of the UIApplication class to open the URL. This method takes three arguments: the URL to open, an options dictionary, and a completion handler.

You may provide other choices for opening the URL using the options dictionary, including whether to open it in the foreground or background and whether to display an alert if it cannot be opened. In this instance, we utilize the default settings by passing an empty dictionary.

When the URL has been opened, a closure called the completion handler is invoked. (or when an error occurs). In this instance, we utilize the default completion handler by passing nil.

Example

Putting it all together, here's an example of how to open a link using the UIApplication class −

import UIKit
class TestController: UIViewController {
    
   private lazy var clickButton: UIButton = {
      let button = UIButton()
      button.addTarget(self, action: #selector(handleButtonClick), for: .touchUpInside)
      button.backgroundColor = .darkGray
      button.setTitle("Click to open link", for: .normal)
      button.setTitleColor(.white, for: .normal)
      button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
      button.layer.cornerRadius = 5
      button.translatesAutoresizingMaskIntoConstraints = false
      return button
   }()
    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }
    
   private func initialSetup() {
        
      view.backgroundColor = .white
      navigationItem.title = "Open Link"
        
      view.addSubview(clickButton)
        
      clickButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
      clickButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
      clickButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      clickButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
   }
    
   @objc private func handleButtonClick() {
      if let url = URL(string: "https://www.tutorialspoint.com") {
         let application = UIApplication.shared
         application.open(url, options: [:], completionHandler: nil)
      }
   }
}

Output

In the example above, we create a URL object using the string. Then, we use the open method of the shared UIApplication instance to open the URL.

This will open the URL in the default browser app on the device, typically Safari on iOS. Note that this method will switch the user out of your app and into the browser app.

Approach 2: Using the SafariServices Framework

  • Step 1 − First, import the SafariServices framework into your Swift file.

  • Step 2 − Create a URL object for the link that you want to open. You can do this using the URL(string:) initializer.

  • Step 3 − Next, create an SFSafariViewController instance and pass in the URL that you want to open.

  • Step 4 − Present the SFSafariViewController using the present(_:animated:completion:) method of your view controller.

The SFSafariViewController will handle displaying the web page and allowing the user to interact with it. When the user is finished browsing, they can simply dismiss the SFSafariViewController to return to your app.

Example

Putting it all together, here's an example of how to open a link using the SafariServices framework −

import UIKit
import SafariServices
class TestController: UIViewController {
    
   private lazy var clickButton: UIButton = {
      let button = UIButton()
      button.addTarget(self, action: #selector(handleButtonClick), for: .touchUpInside)
      button.backgroundColor = .darkGray
      button.setTitle("Click to open link", for: .normal)
      button.setTitleColor(.white, for: .normal)
      button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
      button.layer.cornerRadius = 5
      button.translatesAutoresizingMaskIntoConstraints = false
      return button
   }()
    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }
    
   private func initialSetup() {
        
      view.backgroundColor = .white
      navigationItem.title = "Open Link"
        
      view.addSubview(clickButton)
        
      clickButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
      clickButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
      clickButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      clickButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
   }
    
   @objc private func handleButtonClick() {
      if let url = URL(string: "https://www.tutorialspoint.com") {
         let safariViewController = SFSafariViewController(url: url)
         present(safariViewController, animated: true, completion: nil)
      }
   }
}

Output

This will open the URL in a Safari browser view controller within your app, providing a seamless browsing experience for your users. The SafariServices framework also provides several customization options for the browser view controller, allowing you to tailor the appearance and behavior of the browser to match your app's design.

Conclusion

In conclusion, accessing a link in Swift using the SafariServices framework is an easy and efficient method to give your consumers a flawless surfing experience. The framework's SFSafariViewController class makes it simple to show online information inside of your app while preserving a unified look and feel.

Additionally, the SafariServices framework offers a variety of customization options for the browser view controller, enabling you to modify the browser's look and feel to go along with the design of your app. Although this will move the user out of your app and into the device's default browser app, you may alternatively use the open(_:options:completionHandler:) method of the UIApplication class if you need to open a link outside of your app.

Updated on: 04-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements