Reputation: 1163
I am implementing a browser with UIWebView
with swift for iPhone, iPad. all works fine but the problem is that when users type wrong or not completed URL of their favorite website, it seems that it crashed and dose not render anything. so I want to do somehow if browser could not find the requested page, then it automatically search that exact word on google search engine and shows the result in browser.
here is my codes for this part if needed.
Appreciate any help
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//let urlString:String = urlTextField.text!
var urlString: String = urlTextField.text!
if !urlString.starts(with: "http://") && !urlString.starts(with: "https://") {
urlString = "http://\(urlString)"
}
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
textField.resignFirstResponder()
let path: String = url.path
let ext: String = URL(fileURLWithPath: path ).pathExtension
print(ext as Any)
return true
}
Upvotes: 3
Views: 1118
Reputation: 3939
You can add a check to verify if your urlString contains www
and if not you can set "https://www.google.com/search?q=" url with your text:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let urlString = urlTextField.text else { return true }
if urlString.starts(with: "http://") || urlString.starts(with: "https://") {
loadUrl(urlString)
} else if urlString.contains(“www”) {
loadUrl("http://\(urlString)")
} else {
searchTextOnGoogle(urlString)
}
textField.resignFirstResponder()
//...
return true
}
func loadUrl(_ urlString: String) {
guard let url = URL(string: urlString) else { return }
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
func searchTextOnGoogle(_ text: String) {
// check if text contains more then one word separated by space
let textComponents = text.components(separatedBy: " ")
// we replace space with plus to validate the string for the search url
let searchString = textComponents.joined(separator: "+")
guard let url = URL(string: "https://www.google.com/search?q=" + searchString) else { return }
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
Upvotes: 5