jigar dave
jigar dave

Reputation: 39

How to open url link by using swift?

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

Upvotes: 1

Views: 11709

Answers (2)

Muzahid
Muzahid

Reputation: 5186

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

Upvotes: 5

aaplmath
aaplmath

Reputation: 1807

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.

Upvotes: 8

Related Questions