3

I'm trying to add a google search to my textfield. I've got it so I can look up one or two variables, but after three it crashes. What do I need to change or add to make it work? Here's my code...

func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder()

    var urlString: String = textField.text
    var url = NSURL(string: urlString)

    if (url != nil) {
        url = NSURL(string: "http://www.google.com/search?q=\(urlString)")
        var request = NSURLRequest(URL: url!)
        self.webView.loadRequest(request)
    }
     if url?.scheme == nil {
        var spaces = urlString.rangeOfString(" ")
        var urlStrings = urlString.stringByReplacingCharactersInRange(spaces!, withString: "+")
        var url = NSURL(string: "http://www.google.com/search?q=\(urlStrings)")
        var request = NSURLRequest(URL: url!)
        self.webView.loadRequest(request)
    }
    return false
}
Beth Knight
  • 187
  • 2
  • 15

2 Answers2

2

Your spaces = urlString.rangeOfString(" ") is only finding the first space in the string, and so with a string that has more it will only replace the first space with + and none of the others. You need to use something more along the lines of:

urlString = urlString.replacingOccurrences(of: " ", with: "+")

Here we replace every occurence of the " " character with "+". So to summarise:

var urlString: String = textField.text!
urlString = urlString.replacingOccurrences(of: " ", with: "+")
let url = URL(string: "http://www.google.com/search?q=\(urlString)")
let request = URLRequest(url: url!)
webView.load(request)

n.b. I've force unwrapped some things just for example purposes.

You'll also want to make sure that you trim urlString first in order to remove any excess whitespace (e.g double spaces, or spaces at the beginning and end). See here for how to do that!

Matt Le Fleur
  • 2,708
  • 29
  • 40
0

Update for Swift 5:

var keyword = "Rhinoceros Beetles"
keyword = keyword.replacingOccurrences(of: " ", with: "+")

This should allow you to open the url properly.

Legolas Wang
  • 1,951
  • 1
  • 13
  • 26