8

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)
        }
    }
5
  • just covert url into string & use code as var string = "hello Swift" if string.range(of:"Swift") != nil{ println("exists") } // alternative: not case sensitive if string.lowercased().range(of:"swift") != nil { println("exists") } Commented May 21, 2017 at 11:50
  • @Gagan_iOS i tried doesn't work please read the question properly Commented May 21, 2017 at 11:51
  • try this one ..some time 'contains' does not work. Covert your url into string & check for range as mentioned in first comment. Commented May 21, 2017 at 11:52
  • @Gagan_iOS it's a string please read the question Commented May 21, 2017 at 11:53
  • return URL(string: "http://facebook.com/url/url")?.absoluteString.contains("facebook.com") == true or using the host property return URL(string: "http://facebook.com/url/url")?.host?.contains("facebook.com") == true Commented May 21, 2017 at 12:30

3 Answers 3

23

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
}
Sign up to request clarification or add additional context in comments.

6 Comments

Tip: you don't need the enclosing parenthesis.
@BoilingLime "facebook.com/url/url" will be replaced with NSURL dont worry
@O-mkar Ok, use URL instead NSURL. But URL nor NSURL implement range(of: String). You'll have to unwrap the absoluteString as follow : let urlString = URL(string: "http://facebook.com/url/url")?.absoluteString
Even "simpler" if there's only one condition: just return url.absoluteString.range(of: "facebook.com") != nil or return url.absoluteString.range(of: "facebook.com") == nil depending on the logic you need. ;)
return URL(string: "http://facebook.com/url/url")?.absoluteString.contains("facebook.com") == true
|
5

Works for me as well:

if url.absoluteString.contains("facebook.com") {
    // do something here
}

Comments

0

This works for me

guard url.path.contains("facebook.com")  else { return nil }
 //do what you want

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.