Sah*_*oor 11 ios swift sfsafariviewcontroller
我的代码:
if let url = NSURL(string: "www.google.com") {
    let safariViewController = SFSafariViewController(URL: url)
    safariViewController.view.tintColor = UIColor.primaryOrangeColor()
    presentViewController(safariViewController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
这只在初始化时崩溃,只有异常:
指定的URL具有不受支持的方案.仅支持HTTP和HTTPS URL
当我使用时url = NSURL(string: "http://www.google.com"),一切都很好.我实际上是从API加载URL,因此,我无法确定它们是否会带有前缀http(s)://.
如何解决这个问题?我应该检查并http://始终加前缀,还是有解决方法?
ala*_*hoi 27
URL在制作实例之前尝试检查方案SFSafariViewController.
斯威夫特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)
    }
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特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)
    }
}
Run Code Online (Sandbox Code Playgroud)
        您可以检查的有效性HTTP在您的url字符串制作前NSUrl的对象.
在代码之前放置以下代码,它将解决您的问题(您也可以https以相同的方式检查)
var strUrl : String = "www.google.com"
if strUrl.lowercaseString.hasPrefix("http://")==false{
     strUrl = "http://".stringByAppendingString(strUrl)
}
Run Code Online (Sandbox Code Playgroud)
        我做了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)
}
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           9865 次  |  
        
|   最近记录:  |