Alamofire项目,我在当前函数中获得响应,但在另一个父类中没有响应

时间:2017-02-21 14:10:20

标签: swift alamofire

我正在使用Alamofire API模块开发iOS天气应用程序。我编写了从网上获取天气更新信息的代码,当我在获取信息后打印它时我得到它但我无法在视图控制器中显示该信息。

这是代码。

java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);

1 个答案:

答案 0 :(得分:0)

在ViewController.swift中添加此功能:

func downloadWeatherDetails(callback: @escaping (CurrentWeather)->Void){
        var currentWeather = CurrentWeather()
        let currentWeatherURL = URL(string: CURRENT_WEATHER_URL)!
        Alamofire.request(currentWeatherURL).responseJSON{
            response in
            let result = response.result

            if let dict = result.value as? Dictionary<String, AnyObject>{
                if let name = dict["name"]as? String{
                    currentWeather._cityName=name.capitalized
                    print(currentWeather._cityName)
                }
                if let weather = dict["weather"]as? [Dictionary<String, AnyObject>]{
                    if let main = weather[0]["main"] as? String{
                        currentWeather._weatherType=main.capitalized
                        print(currentWeather._weatherType)
                    }
                }
                if let main = dict["main"] as? Dictionary<String, AnyObject>{
                    if let currentTemp = main["temp"] as? Double{
                        let kelvintoCelcius = (currentTemp - 273.15)

                        currentWeather._currentTemp=kelvintoCelcius
                        print(currentWeather._currentTemp)
                    }
                callback(currentWeather)
            }
        }
    }

将viewDidLoad替换为:

override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadWeatherDetails {
            newWeather in
            currentWeather = newWeather
            self.updateMainUI()
        }
    }