IOS: tableView.reloadData () does not work in swift

I am trying to reload my table view after updating data in Swift, but it does not seem to work. When I change the tab and return, the table view reloads, but not automatically. Here is my code:

override func viewDidLoad() { super.viewDidLoad() // some code refresh(self) } func refresh(sender: AnyObject) { // Reload the data self.tableView.reloadData() } 

I don’t understand why it works in Objective-C, but not in Swift ... I also tried to put:

 dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) 

because I saw this in another post, but it doesn’t work either.

thanks for the help

EDIT: my entire view controller

 class HighwaysViewController: UITableViewController { var highways: [Highway]! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() highways = [Highway]() // On ajoute le "Pull to refresh" refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: Selector("refresh:"), forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshControl!) refresh(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refresh(sender: AnyObject) { // Afficher l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = true // On tĂ©lĂ©charge les autoroutes var url = NSURL(string: "http://theurl.com")! // URL du JSON var request = NSURLRequest(URL: url) // CrĂ©ation de la requĂȘte HTTP var queue = NSOperationQueue() // CrĂ©ation de NSOperationQueue Ă  laquelle le bloc du gestionnaire est distribuĂ© lorsque la demande complĂšte ou Ă©chouĂ© // Envoi de la requĂȘte asynchrone en utilisant NSURLConnection NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in // Gestion des erreurs de connexion if error != nil { // Masquer l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = false println(error.localizedDescription) let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK") errorAlert.show() } else { // RĂ©cupĂ©ration du JSON et gestion des erreurs let json = JSON(data: data) if let highwaysData = json.arrayValue { for highway in highwaysData { var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue) self.highways.append(newHighway) } } } }) if (self.refreshControl!.refreshing) { self.refreshControl!.endRefreshing() } tableView.reloadData() // Here is the problem // Masquer l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = false } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return highways.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("highwayCell", forIndexPath: indexPath) as UITableViewCell // Configure the cell... let tableCell = highways[indexPath.row] let nameLabel = cell.viewWithTag(1) as UILabel let directionLabel = cell.viewWithTag(2) as UILabel nameLabel.text = tableCell.name! directionLabel.text = tableCell.getDirections() return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } 
+6
source share
2 answers

In your refresh function, your download is performed asynchronously using closure, but you update the activity indicator and reload the table outside of closure, so it will be executed until the download is complete. You need to move this code inside the closure and make sure that it runs in the main queue (when updating the user interface).

 func refresh(sender: AnyObject) { // Afficher l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = true // On tĂ©lĂ©charge les autoroutes var url = NSURL(string: "http://theurl.com")! // URL du JSON var request = NSURLRequest(URL: url) // CrĂ©ation de la requĂȘte HTTP var queue = NSOperationQueue() // CrĂ©ation de NSOperationQueue Ă  laquelle le bloc du gestionnaire est distribuĂ© lorsque la demande complĂšte ou Ă©chouĂ© // Envoi de la requĂȘte asynchrone en utilisant NSURLConnection NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in // Gestion des erreurs de connexion if error != nil { // Masquer l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = false println(error.localizedDescription) let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK") errorAlert.show() } else { // RĂ©cupĂ©ration du JSON et gestion des erreurs let json = JSON(data: data) if let highwaysData = json.arrayValue { for highway in highwaysData { var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue) self.highways.append(newHighway) } } } dispatch_async(dispatch_get_main_queue(), { if (self.refreshControl!.refreshing) { self.refreshControl!.endRefreshing() } self.tableView.reloadData() // Masquer l'icĂŽne de chargement dans la barre de status UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) }) } 
+12
source

If you are using a tab bar controller (which looks like you are) and are expecting an update in the table after changing something on another tab, you need to call tableView.reloadData () from inside the destination, instead, viewviewWillAppear () or viewDidAppear ( ) viewDidLoad () is called only once for the life of this view controller.

+1
source

Source: https://habr.com/ru/post/978756/


All Articles