how to open an URL in Swift3

151

openURL has been deprecated in Swift3. Can anyone provide some examples of how the replacement openURL:options:completionHandler: works when trying to open an url?

This question is tagged with ios swift swift3

~ Asked on 2016-09-17 12:32:32

The Best Answer is


393

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

~ Answered on 2016-09-17 12:36:15


37

Above answer is correct but if you want to check you canOpenUrl or not try like this.

let url = URL(string: "http://www.facebook.com")!
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    //If you want handle the completion block than 
    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
         print("Open url : \(success)")
    })
}

Note: If you do not want to handle completion you can also write like this.

UIApplication.shared.open(url, options: [:])

No need to write completionHandler as it contains default value nil, check apple documentation for more detail.

~ Answered on 2016-09-17 12:43:00


Most Viewed Questions: