Any Swift nerds? need help pulling data out of datatask()
Go to solution
Solved by aiwiguna,
Your issue is concurrency, you are accessing the weather array in viewDidLoad, numberOfRowsInSection and cellForRowAt function before the datatask finish because the data task is running in background thread.
Here some change that you need to do to fixed it
override func viewDidLoad() { super.viewDidLoad() getDataFromAPI(){ weather in switch weather { case .success( let gotWeather): self.weather.append(gotWeather) print(gotWeather) DispatchQueue.main.async { self.latitude.text = String(weather[0].latitude) self.longitude.text = String(weather[0].longitude) self.temperature.text! += String(weather[0].currentWeather.temperature) self.windSpeed.text! += String(weather[0].currentWeather.windspeed) self.windDirection.text! += String(weather[0].currentWeather.windDirection) self.elevation.text! += String(weather[0].elevation) self.table.reloadData() } case .failure( let error): print(error) } } // Do any additional setup after loading the view. table.delegate = self table.dataSource = self } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if weather.count != 0 { return weather[0].hourly.time.count } else { return 0 } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! WeatherTableViewCell if weather.count != 0 { cell.loadCell(weather: weather[0], arrayIndex: indexPath.item) } return cell } }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now