Make button open link - Swift

The string you are supplying for the NSURL does not include the protocol information. openURL uses the protocol to decide which app to open the URL.

Adding "http://" to your string will allow iOS to open Safari.

@IBAction func GoogleButton(sender: AnyObject) {
    if let url = NSURL(string: "http://www.google.com"){
        UIApplication.sharedApplication().openURL(url)
    }
}

What your code shows is the action that would occur once the button is tapped, rather than the actual button. You need to connect your button to that action.

(I've renamed the action because GoogleButton is not a good name for an action)

In code:

override func  viewDidLoad() {
  super.viewDidLoad()

  googleButton.addTarget(self, action: "didTapGoogle", forControlEvents: .TouchUpInside)
}

@IBAction func didTapGoogle(sender: AnyObject) {
  UIApplication.sharedApplication().openURL(NSURL(string: "http://www.google.com")!)
}

In IB:

enter image description here

Edit: in Swift 3, the code for opening a link in safari has changed. Use UIApplication.shared().openURL(URL(string: "http://www.stackoverflow.com")!) instead.

Edit: in Swift 4 UIApplication.shared.openURL(URL(string: "http://www.stackoverflow.com")!)


  if let url = URL(string: "your URL") {
        if #available(iOS 10, *){
            UIApplication.shared.open(url)
        }else{
            UIApplication.shared.openURL(url)
        }

    }

Tags:

Ios

Xcode

Swift