如何从UIAlertViewController的处理程序正确打开URL?

时间:2015-06-16 17:33:45

标签: ios swift uiviewcontroller uiapplication

点击提醒按钮后,我正在尝试打开网址。我尝试过不同的方法,但没有一种方法可行。这是我的代码:

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);

如果我放了一些像println这样的简单函数,它可以正常工作。

2 个答案:

答案 0 :(得分:2)

我能够通过创建一个名为" link"的变量来让我工作。用一串url:

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

我将addAction设置为:

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

希望这有助于某人...让我永远想知道如何让处理程序正常工作......

答案 1 :(得分:1)

对于Swift 3用户,这是如何在警报中打开链接的按钮:

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