目前我正在使用 WebView
在我的应用程序中打开链接,但我正在寻找一种在 Safari 中打开链接的选项。
虽然它不是 "嵌入到Swift" 中的一部分,但您可以使用标准的 UIKit
方法来完成它。请查看UIApplication的openUrl(_:)
方法(已弃用)和open(_:options:completionHandler:)
方法。
Swift 4 + Swift 5 (iOS 10及以上)
guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.open(url)
Swift 3(适用于 iOS 9 及以下版本)
guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.openURL(url)
Swift 2.2
guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.sharedApplication().openURL(url)
从iOS 9及以上版本开始,您可以使用SFSafariViewController
来向用户展示(请参见此处的文档)。基本上,您可以在不让用户离开您的应用程序的情况下获得将其发送到Safari的所有好处。要使用新的SFSafariViewController,只需:
import SafariServices
然后在事件处理程序中,以如下方式向用户呈现 Safari 视图控制器:
let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)
Safari浏览器视图将会长成下面这样:
sharedApplication
属性是被禁止的。更多信息请参见:https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionOverview.html#//apple_ref/doc/uid/TP40014214-CH2-SW2 - Baran EmreSwift 5
Swift 5: 使用canOpneURL
检查链接是否有效,如果有效则打开。
guard let url = URL(string: "https://iosdevcenters.blogspot.com/") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
LAUNCH: Launch failure with -10652/ <FSNode 0x10d50cf90> { isDir = y, path = '/Applications/Safari.app' }
。 - JeanNicolas更新,适用于Swift 4:(感谢Marco Weber)
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.shared.openURL(requestUrl as URL)
}
或者采用更加 Swift 风格的方式,使用 guard
:
guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
return
}
UIApplication.shared.openURL(requestUrl as URL)
Swift 3:
您可以通过以下方式隐式地将NSURL检查为可选项:
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.sharedApplication().openURL(requestUrl)
}
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com")
,则使用UIApplication.shared.openURL(requestUrl as URL)
打开该URL。 - Marco WeberSwift 3 & IOS 10.2
UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
Swift 3 和 IOS 10.2
iOS 10 以后,您应该使用:
guard let url = URL(string: linkUrlString) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
@IBAction func openLink {
let pth = "http://www.google.com"
if let url = NSURL(string: pth){
UIApplication.sharedApplication().openURL(url)
}
UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)
Link("Stack Overflow", destination: URL(string: "https://www.stackoverflow.com/")!)
Swift 5
if let url = URL(string: "https://www.google.com") {
UIApplication.shared.open(url)
}