SFSafariViewController崩溃:指定的URL具有不受支持的方案。

我的代码:

if let url = NSURL(string: "www.google.com") { let safariViewController = SFSafariViewController(URL: url) safariViewController.view.tintColor = UIColor.wantoPrimaryOrangeColor() presentViewController(safariViewController, animated: true, completion: nil) } 

这只在初始化时崩溃,只有exception:

指定的URL具有不受支持的方案。 仅支持HTTP和HTTPS URL

当我使用url = NSURL(string: "http://www.google.com") ,一切都很好。 我实际上是从API加载URL,因此,我无法确定它们将以http(s)://为前缀。

如何解决这个问题? 我应该检查并始终为http://前缀,还是有解决方法?

在创建NSUrl对象之前,您可以在url字符串中检查http的可用性。

在代码之前放置以下代码,它将解决您的问题(您也可以以相同的方式检查https

 var strUrl : String = "www.google.com" if strUrl.lowercaseString.hasPrefix("http://")==false{ strUrl = "http://".stringByAppendingString(strUrl) } 

在创建SFSafariViewController的实例之前,请尝试检查URL方案。

斯威夫特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) } } 

斯威夫特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) } } 

我做了Yuvrajsinh和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) }