How to Open a URL in Swift

January 24, 2019

A lot of times your iOS app may need to Deeplink into another app or open up a particular page. Fortunately, there is a function in UIApplication that allows for this functionality.

Let's see how this works.

// Make sure we are working with a valid URL. 
guard let url = URL(string: "http://www.google.com") else {
  return 
}

// Verify our application can open this URL. 
if UIApplication.shared.canOpenURL(url) {
    // Starting iOS 10.0+ the API for opening a URL has changed. 
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

Pro-Tip: Some applications do navigation through Deeplinking only (goodbye ViewController.present!)