Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make button open link - Swift

Tags:

xcode

ios

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: "www.google.com"){         UIApplication.sharedApplication().openURL(url)     } } 

The button is called Google Button and its text is www.google.com

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

like image 364
Thev Avatar asked Jul 25 '15 15:07

Thev


1 Answers

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")!)

like image 184
Paul.s Avatar answered Oct 11 '22 14:10

Paul.s