alucarders
alucarders

Reputation: 31

How to correctly open URL from UIAlertViewController's handler?

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.

Upvotes: 3

Views: 2848

Answers (2)

Achintya Ashok
Achintya Ashok

Reputation: 539

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

Upvotes: 4

MsNichols
MsNichols

Reputation: 1133

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...

Upvotes: 3

Related Questions