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

The*_*eva 41 xcode ios swift

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

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

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

当我按下它时,如何打开链接?

Pau*_*l.s 74

您的代码显示的是点击按钮后将发生的操作,而不是实际按钮.您需要将按钮连接到该操作.

(我已重命名该动作,因为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")!)
}
Run Code Online (Sandbox Code Playgroud)

在IB中:

在此输入图像描述

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

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

  • 对于Swift 3,请使用:`if let url = NSURL(string:"http://www.google.com"){UIApplication.shared.open(url as URL,options:[:],completionHandler:nil)}` (10认同)

Fru*_*eek 22

您为其提供的字符串NSURL不包括协议信息.openURL使用协议来决定打开URL的应用程序.

在字符串中添加"http://"将允许iOS打开Safari.

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

  • 完善!只是我遇到的问题和DUH! (2认同)

Kri*_*kur 10

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

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


Sur*_*ano 10

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

    }
Run Code Online (Sandbox Code Playgroud)

  • 这是一段时间以来的问题,并且有一个声誉良好的接受答案.如果您认为某些内容已发生变化或者您的答案更准确,我建议您添加一个解释. (2认同)
  • 我的答案对于初学者来说更准确. (2认同)

小智 7

对于Swift 3.0:

    if let url = URL(string: strURlToOpen) {
        UIApplication.shared.openURL(url)
    }
Run Code Online (Sandbox Code Playgroud)


Ada*_*aka 7

如果iOS 9或更高版本使用SafariServices更好,那么您的用户将不会离开您的应用程序.

import SafariServices

let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)


osc*_*lon 6

在Swift 4中

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

  • 这与已经给出的答案有什么不同?只是将“Swift 4”放在顶部不会改变任何东西 (2认同)

小智 6

此代码适用于 Xcode 11

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