ios Swift - 在应用程序中打开网页,按钮没有反应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28010518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - open web page in app, button doesn't react
提问by theDC
I created a button to make a call from app:
我创建了一个按钮来从应用程序拨打电话:
@IBAction func callButton(sender: AnyObject) {
if (PhoneNumber != ""){
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://\(PhoneNumber)")!)
}
}
and it works perfectly fine. Strange thing happens when I want to open a web page. I use nearly exactly same code
它工作得很好。当我想打开一个网页时,奇怪的事情发生了。我使用几乎完全相同的代码
@IBAction func openWeb(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "www.google.com")!)
}
But this time button doesn't react and nothing happens. Wherever I was looking for some information about opening web pages in safari from the app, the code was written exactly this way. Do you have any idea where the problem is?
但是这个时间按钮没有反应,什么也没有发生。无论我在哪里寻找有关从应用程序在 safari 中打开网页的信息,代码都是以这种方式编写的。你知道问题出在哪里吗?
Thanks in advance!
提前致谢!
回答by elio.d
missing url scheme
缺少网址方案
UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil)
回答by Aaron Halvorsen
Swift 4, safely unwrapped optional, check if canOpenURL
Swift 4,安全解包可选,检查是否 canOpenURL
if let url = URL(string: "https://www.google.com"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
回答by MrMins
Swift 3 Version
斯威夫特 3 版本
UIApplication.shared.openURL(NSURL(string: "http://google.com")! as URL)
回答by Dustin Spengler
Updated Swift 3.0 version as of iOS 10
从 iOS 10 开始更新 Swift 3.0 版本
let googleURL = NSURL(string: "www.google.com")! as URL
UIApplication.shared.open(googleURL, options: [:], completionHandler: nil)
回答by J. Doe
Swift 4.2.1, iOS 10 and higher
Swift 4.2.1、iOS 10 及更高版本
UIApplication.shared.open(URL(string: "https://google.com")!, options: [:], completionHandler: nil)