使按钮打开链接 - 斯威夫特

时间:2015-07-25 15:45:39

标签: ios xcode swift

这是我现在的代码,取自类似问题的答案。

@IBAction func GoogleButton(sender: AnyObject) {
    if let url = NSURL(string: "www.google.com"){
        UIApplication.sharedApplication().openURL(url)
    }
}

该按钮名为Google按钮,其文字为www.google.com

按下它时如何打开链接?

11 个答案:

答案 0 :(得分:73)

您的代码显示的是点击按钮时出现的操作,而不是实际按钮。您需要将按钮操作连接起来。

(我已重命名该操作,因为GoogleButton不是某个操作的好名称)

在代码中:

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

在IB:

enter image description here

编辑:在Swift 3中,在safari中打开链接的代码已更改。请改用UIApplication.shared().openURL(URL(string: "http://www.stackoverflow.com")!)

编辑:在Swift 4中 UIApplication.shared.openURL(URL(string: "http://www.stackoverflow.com")!)

答案 1 :(得分:21)

您为NSURL提供的字符串不包含协议信息。 openURL使用协议来决定打开网址的应用。

添加" http://"你的字符串将允许iOS打开Safari。

@IBAction func GoogleButton(sender: AnyObject) {
    if let url = NSURL(string: "http://www.google.com"){
        UIApplication.sharedApplication().openURL(url)
    }
}

答案 2 :(得分:10)

因为在iOS 10中不推荐使用openUrl方法,这里是适用于iOS 10的解决方案

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

答案 3 :(得分:8)

  if let url = URL(string: "your URL") {
        if #available(iOS 10, *){
            UIApplication.shared.open(url)
        }else{
            UIApplication.shared.openURL(url)
        }

    }

答案 4 :(得分:7)

对于Swift 3.0:

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

答案 5 :(得分:7)

如果使用iOS 9或更高版本,最好使用SafariServices,这样您的用户就不会离开您的应用。

import SafariServices

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

答案 6 :(得分:5)

在Swift 4中

if let url = URL(string: "http://yourURL") {
            UIApplication.shared.open(url, options: [:])
        }

答案 7 :(得分:4)

您拥有的代码应该可以正常打开链接。我相信,您可能只是将此代码片段复制粘贴到您的代码中。问题是界面中的UI组件(按钮)(很可能是故事板中)没有连接到代码。所以系统不知道,当你按下按钮时,它应该调用这段代码。

为了向系统解释这一事实,请打开您Google Button所在的故事板文件,然后在助理编辑器中打开您的func GoogleButton代码片段所在的文件。右键单击该按钮,然后将该行拖动到代码片段。

如果以编程方式创建此按钮,则应为某些事件添加目标,例如UITouchUpInside。网上有很多例子,所以它应该不是问题:)

更新:正如其他人所说,您还应该为链接添加协议(“http://”或“https://”)。否则它什么都不做。

答案 8 :(得分:2)

对于Swift3,下面的代码工作正常

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

答案 9 :(得分:0)

此代码可用于Xcode 11

if let url = URL(string: "http://www.google.com") {
     UIApplication.shared.open(url, options: [:])
 }

答案 10 :(得分: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)

 }

}

相关问题