21

我的代码:

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

这仅在初始化时崩溃,但有例外:

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

当我使用url = NSURL(string: "http://www.google.com")时,一切都很好。我实际上是从 API 加载 URL,因此,我不能确定它们是否会以http(s)://.

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

4

5 回答 5

41

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)
    }
}

斯威夫特 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)
    }
}
于 2016-02-17T14:07:41.610 回答
13

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

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

var strUrl : String = "www.google.com"
if strUrl.lowercaseString.hasPrefix("http://")==false{
     strUrl = "http://".stringByAppendingString(strUrl)
}
于 2015-09-30T12:00:50.890 回答
10

我结合了 Yuvrajsinh 和 hookokchoi 的答案。

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)
}
于 2016-06-30T19:54:25.927 回答
4

使用 WKWebView 的方法(iOS 11 开始),

class func handlesURLScheme(_ urlScheme: String) -> Bool
于 2018-10-25T05:40:38.187 回答
0

你可以添加到

  NSString* webStringURL = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
  NSURL *URL = [NSURL URLWithString: webStringURL];
于 2021-10-14T13:53:39.603 回答