newdeveloper newdeveloper - 6 months ago 26
Swift Question

How can I set http in searchBar case insensitive?

There is a

searchBar
on top of a
webView
so users can put in new internet addresses. I found when
http
changed to
Http
it doesn't work any more. How can I set
case insensitive
for web address? Thanks!

func searchBarSearchButtonClicked(searchBar: UISearchBar) {

searchBar.resignFirstResponder()

if searchBar.text != nil {

let address = searchBar.text!

if address.containsString("http://") || address.containsString("https://") {

let str = address

if let newUrl = NSURL(string: str) {

let newRequest = NSURLRequest(URL: newUrl)

myWebView.loadRequest(newRequest)

}

} else {

let str = "http://" + String(address)

if let newUrl = NSURL(string: str) {

let newRequest = NSURLRequest(URL: newUrl)

myWebView.loadRequest(newRequest)

}

}

}

}

Answer

Referencing this:

Here is a link to another stack overflow talking about uppercase and lowercase strings.

You should be able to put the whole string to lowercase by doing:

let address = searBar.text!.lowercaseString

That should convert the address string to all lowercase. You might also want to consider changing the capitalization for the search bar box to be disabled.

Another solution might be to check if address.contains("Http://")

Best, Joe