2

I'm trying to make a clickable link over a button. I made this using some Internet help but it didn't work :

    @IBAction func linkClicked(sender: AnyObject) {
    openUrl("http://fr.envisite.net/t5exce")
}
func openUrl(url:String!) {

    let targetURL=NSURL(fileURLWithPath: url)

    let application=UIApplication.sharedApplication()

    application.openURL(targetURL);

}

It doesn't do anything, no error, just the button doesn't get me on Safari (I use the iOS simulator)

Julien Quere
  • 2,407
  • 16
  • 21
Orionss
  • 725
  • 2
  • 10
  • 26
  • Possible duplicate of [How to launch safari and open URL from iOS app](http://stackoverflow.com/questions/12416469/how-to-launch-safari-and-open-url-from-ios-app) – Thanh-Nhon Nguyen Sep 08 '16 at 14:41

1 Answers1

6

You're creating a file URL with a web url string. Use the NSURL String constructor instead.

@IBAction func linkClicked(sender: AnyObject) {
    openUrl("http://fr.envisite.net/t5exce")
}

func openUrl(urlStr:String!) {

     if let url = NSURL(string:urlStr) {
UIApplication.sharedApplication().openURL(url)
}

   }

Swift3

@IBAction func linkClicked(sender: Any) {
    openUrl(urlStr: "http://fr.envisite.net/t5exce")
}

func openUrl(urlStr: String!) {
    if let url = URL(string:urlStr), !url.absoluteString.isEmpty {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143