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?

5
  • Your method does not send a request at all... It just parses the string and prints the URL out. Commented Mar 9, 2020 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 Commented Mar 9, 2020 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 Commented Mar 9, 2020 at 18:04
  • 1
    What cityNameString did you give it? By answering this, you are providing a minimal reproducible example, which helps us see what's wrong with your code. Commented Mar 9, 2020 at 18:22
  • I found the solution by following this question Commented Mar 9, 2020 at 18:37

2 Answers 2

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
}

Sign up to request clarification or add additional context in comments.

Comments

0

Check for space and remove it from String

 let cityName = "  My CityName  "
 let trimmed = cityName.trimmingCharacters(in: .whitespacesAndNewlines)

2 Comments

Thanks, I also found the solution for trimming here: stackoverflow.com/questions/28570973/…
This won't work either because it does not remove the inner space

Your Answer

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