0

I'm creating a function which makes an API request. The function receives a parameter and put it inside the API call. It is like this:

static func queryCities(cityNameString : String, completion: @escaping (City)->()){
    let urlString = "http://api.geonames.org/searchJSON?q=\(cityNameString)&username=myusername"
    guard let url = URL(string: urlString) else {return}
    print(url)

}

But only when I try to convert my String into a URL the function doesn't return anything. I need to precise that the API call is working well if I paste it in safari. How can I solve this problem?

  • Your method does not send a request at all... It just parses the string and prints the URL out. – Sweeper Mar 09 '20 at 18:00
  • Yes I omitted the part where I did stuff because when I print out the url it doesn't print out anything and I want to know why is that. Basically it seems that the URL(string: urlString) constructor is not doing its job –  Mar 09 '20 at 18:03
  • 2
    Be aware that `URL(string:` returns `nil` if the city name contains a space character. Basically you have to (percent)encode the string – vadian Mar 09 '20 at 18:04
  • 1
    What `cityNameString` did you give it? By answering this, you are providing a [mcve], which helps us see what's wrong with your code. – Sweeper Mar 09 '20 at 18:22
  • I found the solution by following this question –  Mar 09 '20 at 18:37

2 Answers2

1

I would recommend using URLComponents to assemble your URL:

static func queryCities(cityNameString : String, completion: @escaping (City)->()) {
    var components = URLComponents(string: "http://api.geonames.org/searchJSON")
    components?.queryItems = [
        URLQueryItem(name: "q", value: cityNameString),
        URLQueryItem(name: "username", value: "myusername")
    ]

    guard let url = components?.url else { return }
    print(url)

    // do the http request here
}

Gereon
  • 17,258
  • 4
  • 42
  • 73
0

Check for space and remove it from String

 let cityName = "  My CityName  "
 let trimmed = cityName.trimmingCharacters(in: .whitespacesAndNewlines)
Harish
  • 2,496
  • 4
  • 24
  • 48
  • Thanks, I also found the solution for trimming here: https://stackoverflow.com/questions/28570973/how-should-i-remove-all-the-leading-spaces-from-a-string-swift –  Mar 09 '20 at 18:36
  • 2
    This won't work either because it does not remove the inner space – vadian Mar 09 '20 at 18:41