Thevesh Theva Thevesh Theva - 2 years ago 231
iOS Question

Make button open link - Swift

This is the code I have now, taken from an answer to a similar question.

@IBAction func GoogleButton(sender: AnyObject) {
if let url = NSURL(string: ""){

The button is called Google Button and its text is

How do I make it open the link when I press it?

Answer Source

What you have shown in your code the the action that would occur once the button is tapped not the actual button. You need to connect your button to that action.

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

In code:

override func  viewDidLoad() {

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

@IBAction func didTapGoogle(sender: AnyObject) {
  UIApplication.sharedApplication().openURL(NSURL(string: "")!)

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: "")!) instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download