我的代码:
if let url = NSURL(string: "www.google.com") {
let safariViewController = SFSafariViewController(URL: url)
safariViewController.view.tintColor = UIColor.primaryOrangeColor()
presentViewController(safariViewController, animated: true, completion: nil)
}
只有异常时才会在初始化时崩溃:
指定的网址具有不受支持的方案。仅支持HTTP和HTTPS URL
当我使用url = NSURL(string: "http://www.google.com")
时,一切都很好。
我实际上正在从API加载URL,因此,我不能确定它们将以http(s)://
为前缀。
如何解决这个问题?我应该检查并始终为http://
添加前缀,还是有解决方法?
答案 0 :(得分:26)
在制作URL
的实例之前,请尝试检查SFSafariViewController
的方案。
Swift 3 :
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
// not a valid URL
return
}
if ["http", "https"].contains(url.scheme?.lowercased() ?? "") {
// Can open with SFSafariViewController
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true, completion: nil)
} else {
// Scheme is not supported or no scheme is given, use openURL
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
Swift 2 :
func openURL(urlString: String) {
guard let url = NSURL(string: urlString) else {
// not a valid URL
return
}
if ["http", "https"].contains(url.scheme.lowercaseString) {
// Can open with SFSafariViewController
let safariViewController = SFSafariViewController(URL: url)
presentViewController(safariViewController, animated: true, completion: nil)
} else {
// Scheme is not supported or no scheme is given, use openURL
UIApplication.sharedApplication().openURL(url)
}
}
答案 1 :(得分:7)
在创建url
对象之前,您可以在NSUrl
字符串中检查 http 的可用性。
将以下代码放在代码之前,它将解决您的问题(您也可以同样方式检查https
)
var strUrl : String = "www.google.com"
if strUrl.lowercaseString.hasPrefix("http://")==false{
strUrl = "http://".stringByAppendingString(strUrl)
}
答案 2 :(得分:7)
我做了Yuvrajsinh& amp;&; hoseokchoi的答案。
func openLinkInSafari(withURLString link: String) {
guard var url = NSURL(string: link) else {
print("INVALID URL")
return
}
/// Test for valid scheme & append "http" if needed
if !(["http", "https"].contains(url.scheme.lowercaseString)) {
let appendedLink = "http://".stringByAppendingString(link)
url = NSURL(string: appendedLink)!
}
let safariViewController = SFSafariViewController(URL: url)
presentViewController(safariViewController, animated: true, completion: nil)
}
答案 3 :(得分:1)
使用WKWebView的方法(从iOS 11开始),
class func handlesURLScheme(_ urlScheme: String) -> Bool