Check if an URL has got http:// prefix

Viewed 27705


In my application, when the user add an object, can also add a link for this object and then the link can be opened in a webView.
I tried to save a link without http:// prefix, then open it in the webView but that can't open it!
Before webView starts loading, is there a method to check if the URL saved has got http:// prefix? And if it hasn't got it, how can I add the prefix to the URL?
Thanks!

9 Answers

In function 'navigationAction' of WKNavigationDelegate

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            if let url = navigationAction.request.url {
                decisionHandler(.cancel)
                var urlString = url.absoluteString
                if urlString.lowercased().hasPrefix("http://") == false {
                    urlString = String(format: "http://%@", urlString)
                }

                let safariViewController = SFSafariViewController(url: url)
                presentInFullScreen(safariViewController, animated: true, completion: nil)
            } else {
                decisionHandler(.allow)
            }
        } else {
            decisionHandler(.allow)
        }
    }
Related