How to open url link by using swift?

jigar dave picture jigar dave · Aug 1, 2018 · Viewed 7.6k times · Source

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

Answer

aaplmath picture aaplmath · Aug 1, 2018

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.