openURL 和 canOpenURL 之间的区别

Difference between openURL & canOpenURL

我需要在 safari 浏览器中打开 link 但我有疑问,我应该使用哪种方法? openURL/opencanOpenURL。 谁能帮我解释一下这两种功能之间的实际区别是什么?

 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, *)
    }

canOpenURL(_:)

Returns 一个布尔值,指示 URL 的方案是否可以由安装在设备上的某些应用程序处理。

打开URL(_:)

尝试在指定的 URL 打开资源。

openURL(_:) 已弃用 - iOS 10.0

改用open(_:options:completionHandler:)方法。 示例:

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.

canOpenURL : returns bool, url 是否可以打开

示例:

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

openURL : 打开 url.

因为它已从 ios 10 中弃用。所以新功能是 openURL:options:completionHandler:

例子

func open(scheme: String) {
  if let url = URL(string: scheme) {
    UIApplication.shared.open(url, options: [:], completionHandler: {
      (success) in
      print("Open \(scheme): \(success)")
    })
  }
}