这是我现在的代码,取自类似问题的答案.
@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")!)
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)
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)
小智 7
对于Swift 3.0:
if let url = URL(string: strURlToOpen) {
UIApplication.shared.openURL(url)
}
Run Code Online (Sandbox Code Playgroud)
如果iOS 9或更高版本使用SafariServices更好,那么您的用户将不会离开您的应用程序.
import SafariServices
let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
在Swift 4中
if let url = URL(string: "http://yourURL") {
UIApplication.shared.open(url, options: [:])
}
Run Code Online (Sandbox Code Playgroud)
小智 6
此代码适用于 Xcode 11
if let url = URL(string: "http://www.google.com") {
UIApplication.shared.open(url, options: [:])
}
Run Code Online (Sandbox Code Playgroud)