Ankit Baid Ankit Baid - 26 days ago 15
Swift Question

execute function after function is not working swift 3

This is the function which i want to get execute after downloading all details and another function whcih is to update UIElements to after downloading. This function is inside "CurrentWeather.swift"

func downloadWeatherDetails(completed: ( () -> () )){
// tell Alimofire where to download
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{
self._cityName = name.capitalized
print(self._cityName)
}

if let weather = dict["weather"] as? [Dictionary<String, AnyObject>]{
if let main = weather[0]["main"] as? String{
self._weatherType = main.capitalized
print(self._weatherType)
}
}

if let main = dict["main"] as? Dictionary<String, AnyObject>{
if let currentTemperature = main["temp"] as? Double {
let kelvinToFarenhitePreDevision = (currentTemperature * (9/5) - 459.67 )
let kelvinToFarenhite = Double(round(10 * kelvinToFarenhitePreDevision/10))
self._currentTemp = kelvinToFarenhite
print(self._currentTemp)
}
}


}


}
completed()
}


}

and this function is to update UIEmelents

func updateMainUI(){

dateLabel.text = currentWeather.date
currentTempLabel.text = "\(currentWeather.currentTemp)"
currentWeatherTypeLabel.text = currentWeather.weatherType
locationLabel.text = currentWeather.cityName
currentWeatherImage.image = UIImage(named: currentWeather.weatherType)
}


and this is to call them on Override func viewDidLoad()

override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self

currentWeather.downloadWeatherDetails { () -> () in
self.updateMainUI()
}
}


now when i am executing this its not updating UI data
but its printing them inside console

can anybody help me with this issue

Answer

You are calling completed() before your request is completed.

        completed() //<- you need to call the completion handler inside the closure.
    }
    //completed() //<- this would be called before completion
}

I haven't checked other parts of your code, but at least you need to fix this.