Difference between openURL & canOpenURL
Asked Answered
H

2

5

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, *)
    }
Hedgepeth answered 1/1, 2018 at 9:51 Comment(2)
Which version of Xcode and swift you used?Mantelpiece
xcode 9.2 (swift 4)Hedgepeth
F
10

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.

Foundry answered 1/1, 2018 at 9:54 Comment(1)
Important note if you use canOpenURL(_:) : 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 installedMonney
I
3

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)")
    })
  }
}
Iquitos answered 1/1, 2018 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.