I have Swift code to call on the Open Weather API.The code works well with any one word city (eg Rome), but balks at a city with more than one word (eg New York).
I have some print statements to show console output at various steps and they all work with a single word input city. The console output shows the expected JSON string.
With a city like New York or Los Angeles, I get the console print of the URL, but no JSON.
I copy and paste the NY console URL string into a browser and the site responds appropriately. Value of myKey redacted.
Output for Paris
URL is: https://api.openweathermap.org/data/2.5/weather?&appid=myKey&units=metric&q=Paris
JSON is:
\"weather\":[{\"id\":701,\"main\":\"Mist\",\"description\":\"mist\",\"icon\":\"50n\"}],\"base\":\"stations\",\"main\":{\"temp\":4.76,\"feels_like\":4.76,\"temp_min\":3.08,\"temp_max\":6.03,\"pressure\":1024,\"humidity\":92},\"visibility\":5000,\"wind\":{\"speed\":1.03,\"deg\":310},\"clouds\":{\"all\":90},\"dt\":1636571558,\"sys\":{\"type\":2,\"id\":2041230,\"country\":\"FR\",\"sunrise\":1636527115,\"sunset\":1636561035},\"timezone\":3600,\"id\":2988507,\"name\":\"Paris\",\"cod\":200}")
extracts of JSON:
CITY is Paris
TEMP IS 4.76
mist
for New York:
https://api.openweathermap.org/data/2.5/weather?&appid=myKey&units=metric&q=New York
No JSON
Any ideas?
Thanks!
Sleeper
What I have tried:
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?&appid=myKey&units=metric"
func fetchWeather (cityName:String) {
let urlString = ("\(weatherURL)&q=\(cityName)")
print("**URL*** \(urlString)")
performRequest(urlString: urlString)
}
func performRequest(urlString: String) {
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler: handle(data:response:error:))
task.resume()
}
}
func handle(data: Data?, response: URLResponse?, error: Error? ) ->Void {
if error != nil{
print(error!)
return
}
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
print(dataString)
parseJSON(weatherData: safeData)
}
func parseJSON (weatherData: Data) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
print("CITY is \(decodedData.name)")
print(" TEMP IS \(decodedData.main.temp)")
print("\(decodedData.weather[0].description)")
} catch {
print(error)
}
}
}
}