3

I'm trying to open URL after clicking on alert's button. I've tried different approaches, but none of it worked. Here's my code:

let alert = UIAlertController(title: "Warning", message: "Do you want to open the link?", preferredStyle: .Alert);

alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil));
let okAction = UIAlertAction(title: "Open in Safari", style: .Default) {(action) in
     UIApplication.sharedApplication().openURL(NSURL(string: "www.google.com")!);
     return;
});
alert.addAction(okAction);

self.presentViewController(alert, animated: true, completion: nil);

If I put some simple function like println, it works fine.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
alucarders
  • 31
  • 1
  • 3

2 Answers2

4

For Swift 3 Users, this is how to have a button that open a link in an alert:

let action: UIAlertAction = UIAlertAction(title: "SomeTitle", style: .default, handler: {
   (action) in
      UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil)
      NSLog("Opening link")
 })
Jay Patel
  • 2,642
  • 2
  • 18
  • 40
Achintya Ashok
  • 521
  • 4
  • 9
3

I was able to get mine to work by creating a variable called "link" with a string of the url:

let link = 'http://google.com"

and i set my addAction to look like:

showAlert.addAction(UIAlertAction(title: "Download", 
   style: UIAlertActionStyle.Default, handler: { 
       (action:UIAlertAction!) -> Void in 
            UIApplication.sharedApplication().openURL(NSURL(string: link)!)
                  print("something here... button click or action logging")
 }))

hope this helps someone... took me forever to figure outg how tgo get the handler to work right...

MizAkita
  • 1,115
  • 5
  • 21
  • 52