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, *)
}
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.
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)")
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With