user12422782
user12422782

Reputation:

get url from String using URL(string: ) constructor

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?

Upvotes: 0

Views: 62

Answers (2)

Gereon
Gereon

Reputation: 17844

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
}

Upvotes: 1

Harish
Harish

Reputation: 2512

Check for space and remove it from String

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

Upvotes: 0

Related Questions