50

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?

1
  • 1
    Swift 3: UIApplication.shared.open(NSURL(string: "google.com")! as URL, options: [:], completionHandler: nil)
    – kavehmb
    Commented Feb 24, 2017 at 4:45

13 Answers 13

81

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

3
  • Wow, I didn't know, that it shows a list of methods, if you ctrl-drag to the View Controller icon. Thanks, this is useful :) Commented Jul 25, 2015 at 16:05
  • 1
    "'openURL' was deprecated in iOS 10.0: Please use openURL:options:completionHandler: instead" - I'm new to Swift (& Swift 3), I'm not really sure what that syntax is. Suffice to say, whatever. Commented Oct 8, 2016 at 2:27
  • 10
    For Swift 3 use this: if let url = NSURL(string: "http://www.google.com"){ UIApplication.shared.open(url as URL, options: [:], completionHandler: nil) } Commented Oct 12, 2016 at 19:43
23

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)
    }
}
1
  • 2
    perfect! just the problem i was having and DUH!
    – jakeatwork
    Commented Dec 6, 2015 at 5:30
14
  if let url = URL(string: "your URL") {
        if #available(iOS 10, *){
            UIApplication.shared.open(url)
        }else{
            UIApplication.shared.openURL(url)
        }

    }
3
  • 2
    The question it's from a while back and has a reputable accepted answer. If you believe something has changed or perhaps your answer is more accurate, I recommend you to add an explanation. Commented Oct 26, 2017 at 10:45
  • 2
    My answer is more accurate for beginners. Commented Oct 26, 2017 at 12:48
  • 1
    Then I suggest you to indicate so on the answer. Commented Oct 26, 2017 at 14:26
10

as openUrl method is deprecated in iOS 10, here is solution for iOS 10

let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString) as! URL
UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
9

In Swift 4

if let url = URL(string: "http://yourURL") {
            UIApplication.shared.open(url, options: [:])
        }
1
  • 2
    How is this any different to answers already given? Just putting "Swift 4" at the top doesn't change anything Commented Aug 19, 2018 at 16:58
9

if iOS 9 or higher it's better to use SafariServices, so your user will not leave your app.

import SafariServices

let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)
7

For Swift 3.0:

    if let url = URL(string: strURlToOpen) {
        UIApplication.shared.openURL(url)
    }
6

This code works with Xcode 11

if let url = URL(string: "http://www.google.com") {
     UIApplication.shared.open(url, options: [:])
 }
2
  • Welcome to StackOverflow :) Thank you for contributing, but the next time you answer something, please describe your solution a bit more. Refer to How to Answer to read some useful tips for answering questions :) Commented Aug 28, 2019 at 15:02
  • Working for me...... Commented Dec 29, 2021 at 5:37
4

The code that you have should open the link just fine. I believe, that you probably just copy-pasted this code fragment into your code. The problem is that the UI component (button) in the interface (in storyboard, most likely) is not connected to the code. So the system doesn't know, that when you press the button, it should call this code.

In order to explain this fact to the system, open the storyboard file, where your Google Button is located, then in assistant editor open the file, where your func GoogleButton code fragment is located. Right-click on the button, and drag the line to the code fragment.

If you create this button programmatically, you should add target for some event, for instance, UITouchUpInside. There are plenty of examples on the web, so it shouldn't be a problem :)

UPDATE: As others noted already, you should also add a protocol to the link ("http://" or "https://"). It will do nothing otherwise.

2

For Swift3 , below code is working fine

@IBAction func Button(_ sender: Any) { 
   UIApplication.shared.open(urlStore1, options: [:], completionHandler: nil)     
 }
1

Actually You Can Use It Like This In Your Action Button Works For Swift 5 :


    guard let settingsUrl = URL(string:"https://yourLink.com") else {
        return
    }
    UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
}
0
// How to open a URL in Safari

import SafariServices \\ import 

 @IBAction func google(_ sender: Any) 

{ 

if let url = URL(string: "https://www.google.com")
 {

   let safariVC = SFSafariViewController(url: url)
   present(safariVC, animated: true, completion: nil)

 }

}

0

I made this way:

I imported SafariServices

import SafariServices

First step: I defined a button just above viewDidLoad:

let myButton = UIButton()

Second step: I called a function inside viewDidLoad:

    func setupMyButton() {
    view.addSubview(myButton)

            myButton.configuration = .plain()
            myButton.configuration?.cornerStyle = .capsule
            myButton.configuration?.title = "Go to Google"
            myButton.addTarget(self, action: #selector(selector), for: .touchUpInside)
            
            myButton.translatesAutoresizingMaskIntoConstraints = false
            
            NSLayoutConstraint.activate([
            myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myButton.widthAnchor.constraint(equalToConstant: 200),
            myButton.heightAnchor.constraint(equalToConstant: 50),
            ])

}

Third step: At the bottom of the scope, I called an @objc func to use as selector. (Outside viewDidLoad)

@objc func selector() {
if let url = URL(string: "https://www.google.com")
 {

   let safariVC = SFSafariViewController(url: url)
   present(safariVC, animated: true, completion: nil)

 }
}

And I did not forget to call my func at the beginning of the viewDidLoad:

setupMyButton()

A dude named PRAVEEN BHATI helped me at the third step. Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.