I am fairly new to developing apps for iOS, and the Swift language in itself. I'm trying to learn how to make HTTP requests for future projects, but to no avail.
My current approach is through using Alamofire and SwiftyJSON, which is configured through Cocoapods. The code below is for a class which sends a GET request to openweathermap.org
, which given the name for a city, returns JSON that contains the current temperature of the city.
However, it seems that no matter what I input as the city name (see second-last line), the only thing printed in the last line is 0.0
. Through inspection of the .playground
file I put this in, the request doesn't seem to activate at all - the value never changes from the default value I set it, Float(0)
.
import Alamofire
import SwiftyJSON
// City temperature class: given a city name, the class will
// automatically generate the city's temperature.
class City {
var name: String
var temperature: Float
// Helper function, get request through Alamofire is here
private func getTemperature(completionHandler: @escaping (Error?, String?) -> ()) {
let key = "" // Insert key for openweathermap.org here
let url = "https://api.openweathermap.org/data/2.5/weather?q=\(self.name)&units=metric&appid=\(key)"
Alamofire.request(url, method: .get).responseJSON { response in
switch response.result {
case .success(let value):
completionHandler(nil, value as? String)
case .failure(let error):
completionHandler(error, nil)
}
}
}
// Initialisation function, this will call getTemperature()
// to set self.temperature
init(name: String) {
// All class variables have to be set - if not set,
// Xcode refuses to run playground file
self.name = name
self.temperature = Float(0)
getTemperature { (error, response) in
if error == nil {
let json = JSON(response as String!)
self.temperature = json["main"]["temp"].float!
} else {
print(error!.localizedDescription)
}
}
}
}
let city = City(name: "Sydney")
print(city.temperature) // Doesn't matter what name I put in, output is always 0.0