Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i check if url string contains a word in swift?

I'm trying to forward the web view to a local file if URL doesn't contain words I want I tried many things contains and rangeofstrings didn't work for me.

  if let url = "http://facebook.com/url/url"{

        if url.contains("facebook.com") || url.contains("nocontent") || url.contains("nointernet") || url.contains("paypal.com"){
            //Doing something here
            return true
        }else{

            let htmlFile = Bundle.main.path(forResource: "nocontent", ofType: "html")
            let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
            webView.loadHTMLString(html!, baseURL: nil)
        }
    }
like image 285
O-mkar Avatar asked May 21 '17 11:05

O-mkar


2 Answers

This should do the job :

if let url = URL(string: "http://facebook.com/url/url") {

    if url.absoluteString.range(of: "facebook.com") != nil {

        return true
    }

    return false
}
like image 67
BoilingLime Avatar answered Oct 21 '22 02:10

BoilingLime


Works for me as well:

if url.absoluteString.contains("facebook.com") {
    // do something here
}
like image 3
IvanPavliuk Avatar answered Oct 21 '22 01:10

IvanPavliuk