I am calling the API service from my viewController using a private function.
private func updateCells() -> Void {
let cities: [String] = ["New York", "London", "Tokyo", "Toronto", "Sydney", "Paris"]
for cityName in cities {
print(cityName)
queryService.getSearchResults(cityName: cityName){results, errorMessage in
if let results = results{
self.myCity = results
self.CityGrid.reloadData()
self.list.append(results)
print("Test -> name: \(results.name)")
print("Test -> description: \(results.description)")
print("Test -> currentTemp: \(Int(results.currentTemperature))")
print(self.list[0])
}
if !errorMessage.isEmpty {
print("Search error: " + errorMessage)
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
Here the QueryService class function to handle the API calls.
func getSearchResults(cityName: String, completion: @escaping QueryResult) {
dataTask?.cancel()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(cityName)&units=metric&appid=zezfac1ecbe0511f1ac192add4ff112e")!
dataTask = defaultSession.dataTask(with: url) { [weak self] data, response, error in
defer {
self?.dataTask = nil
}
if let error = error {
self?.errorMessage += "Default Task Error: " + error.localizedDescription + "\n"
} else if
let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 {
self?.updateRestults(data)
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "")
}
}
else if let res = response as? HTTPURLResponse,
res.statusCode == 404{
self?.errorMessage = "City Not Found"
DispatchQueue.main.async {
completion(self?.location, self?.errorMessage ?? "Not Found")
}
//print("City Not found")
}
}
dataTask?.resume()
}
But I get the error Unexpectedly found nil while unwrapping an Optional value. But if I use a hard-coded string it works fine. What am I doing wrong here? Since the cities array is of type String,