Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between openURL & canOpenURL

Tags:

ios

swift

openurl

i need to open a link in safari browser but i have doubt, which method should i use ? openURL/open or canOpenURL. Can anyone please help me to explain what actual difference between both function?

 if #available(iOS 10.0, *) {
       UIApplication.shared.open(URL(string: urlStr)!, options: [:], completionHandler: nil)
       UIApplication.shared.canOpenURL(URL(string: urlStr)!)

    } else {
        UIApplication.shared.openURL(URL(string: urlStr)!) //introduced: 2.0, deprecated: 10.0,

        UIApplication.shared.canOpenURL(URL(string: urlStr)!) // available(iOS 3.0, *)
    }
like image 384
MAhipal Singh Avatar asked Sep 03 '26 06:09

MAhipal Singh


2 Answers

canOpenURL(_:)

Returns a Boolean value indicating whether or not the URL’s scheme can be handled by some app installed on the device.

openURL(_:)

Attempts to open the resource at the specified URL.

openURL(_:) Deprecated - iOS 10.0

Use the open(_:options:completionHandler:) method instead. Example:

if UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10.0, *) {
         UIApplication.shared.open(url, options: [:], completionHandler: { (success) in

         })
    } else {
         UIApplication.shared.openURL(url)
    }
}

If your app is linked on or after iOS 9.0, you must declare the URL schemes you pass to this method by adding the LSApplicationQueriesSchemes key to your app's Info.plist file. This method always returns false for undeclared schemes, whether or not an appropriate app is installed.

like image 146
Harshal Valanda Avatar answered Sep 04 '26 21:09

Harshal Valanda


canOpenURL : It returns the bool, whther the url can be opened or not.

Example:

func schemeAvailable(scheme: String) -> Bool {
    if let url = URL(string: scheme) {
        return UIApplication.shared.canOpenURL(url)
    }
    return false
}

openURL : It opens the url.

As it is deprecated from ios 10. so new func is openURL:options:completionHandler:

Example

func open(scheme: String) {
  if let url = URL(string: scheme) {
    UIApplication.shared.open(url, options: [:], completionHandler: {
      (success) in
      print("Open \(scheme): \(success)")
    })
  }
}
like image 25
dahiya_boy Avatar answered Sep 04 '26 21:09

dahiya_boy