xcode 如何使用swift打开url链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51623847/
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
How to open url link by using swift?
提问by jigar dave
i want to go to a url by clicking on button. I tried using 'UISharedapplication'and also through the method below mentioned but none works. Please help. Thanks.
我想通过单击按钮转到 url。我尝试使用“UISharedapplication”并通过下面提到的方法但没有任何效果。请帮忙。谢谢。
@IBAction func Displayurl(_ sender: Any) {
UIApplication.shared.canOpenURL(NSURL (string: "http://www.apple.com")! as URL)
}
回答by aaplmath
The issue is that UIApplication
's canOpenURL()
method simply returns whethera URL canbe opened, and does not actually open the URL. Once you've determined whether the URL can be opened (by calling canOpenURL()
, as you have done), you must then call open()
on the shared UIApplication
instance to actually open the URL. This is demonstrated below:
问题是 thatUIApplication
的canOpenURL()
方法只是返回一个 URL是否可以打开,并没有实际打开 URL。一旦确定了 URL 是否可以打开(通过调用canOpenURL()
,就像您所做的那样),您必须然后调用open()
共享UIApplication
实例来实际打开 URL。这在下面演示:
if let url = URL(string: "http://www.apple.com") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
}
open()
also takes an optional completionHandler
argument with a single success
parameter that you can choose to implement to determine if the URL was successfully opened.
open()
还采用completionHandler
带有单个success
参数的可选参数,您可以选择实施该参数以确定 URL 是否已成功打开。
回答by iMuzahid
canOpenURL(_:)
method is used whether there is an installed app that can handle the url scheme. To open the resource of the specified URL use the open(_:options:completionHandler:)
method. As for example
canOpenURL(_:)
方法用于是否有可以处理 url 方案的已安装应用程序。要打开指定 URL 的资源,请使用open(_:options:completionHandler:)
方法。例如
if let url = URL(string: "apple.com") {
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
For more info check the documentation here https://developer.apple.com/documentation/uikit/uiapplication/1622961-openurl
有关更多信息,请查看此处的文档https://developer.apple.com/documentation/uikit/uiapplication/1622961-openurl