1

i want to go to a url by clicking on button. I tried using 'UISharedapplication'and also through the method below mentioned but none works. Please help. Thanks.

@IBAction func Displayurl(_ sender: Any) {

    UIApplication.shared.canOpenURL(NSURL (string: "http://www.apple.com")! as URL)
}
    
double-beep
  • 5,031
  • 17
  • 33
  • 41
jigar dave
  • 39
  • 1
  • 1
  • 11

2 Answers2

8

The issue is that UIApplication's canOpenURL() method simply returns whether a URL can be opened, and does not actually open the URL. Once you've determined whether the URL can be opened (by calling canOpenURL(), as you have done), you must then call open() on the shared UIApplication instance to actually open the URL. This is demonstrated below:

if let url = URL(string: "http://www.apple.com") {
    if UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: [:])
    }
}

open() also takes an optional completionHandler argument with a single success parameter that you can choose to implement to determine if the URL was successfully opened.

aaplmath
  • 1,717
  • 1
  • 14
  • 27
  • let url = URL(string: "https://www.google.com") let vc = SFSafariViewController(url: url!) present(vc, animated: true, completion: nil) solved this too by adding 'Safariservice' framework. Thanks – jigar dave Aug 01 '18 at 00:59
5

canOpenURL(_:) method is used whether there is an installed app that can handle the url scheme. To open the resource of the specified URL use the open(_:options:completionHandler:) method. As for example

 if let url = URL(string: "apple.com") {
        if UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

For more info check the documentation here https://developer.apple.com/documentation/uikit/uiapplication/1622961-openurl

Muzahid
  • 5,072
  • 2
  • 24
  • 42