类变量无法使用Alamofire,SwiftyJSON进行更新

时间:2018-01-06 12:41:15

标签: swift alamofire swifty-json

我很擅长为iOS开发应用程序,以及Swift语言本身。我正在尝试学习如何为未来的项目提出HTTP请求,但无济于事。

我目前的方法是使用Alamofire和SwiftyJSON,它是通过Cocoapods配置的。下面的代码是针对一个向openweathermap.org发送GET请求的类,该请求给出了城市的名称,返回包含城市当前温度的JSON。

然而,似乎无论我输入什么作为城市名称(见倒数第二行),最后一行中打印的唯一内容是0.0。通过检查我放入的.playground文件,请求似乎根本没有激活 - 值永远不会改变我设置的默认值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

0 个答案:

没有答案