简体   繁体   中英

tableView is not updating until i tap another tab and get back - swift

I'm new in iOS , i'm populating tableView data dynamically from a web source by parsing JSON data . But the problem is when i visit that tab first time its showing nothing . After i visit another tab and get back , its showing the data properly on tableView .

Here is my code

import UIKit

class BranchViewController: UITableViewController , UISearchBarDelegate, UISearchDisplayDelegate {

    var branches = [Branch]()
    var filteredBranch = [Branch]()
    var BranchArray = [BranchTable]()
    var BranchLocationArray = [BranchLocation]()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.tableView!.delegate = self
        self.tableView!.dataSource = self

        let url = NSURL(string: "http://rana.ninja/branches.php")

        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            println(NSString(data: data, encoding: NSUTF8StringEncoding))
            var error: NSError?
            let jsonData: NSData = data /* get your json data */
            let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

            if let name: AnyObject = json["name"]  {
                for var index = 0; index < name.count; ++index {
                    var Name : String  = name[index] as NSString
                    self.branches.append(Branch(name: Name))
                    println(Name)
                }
            }
        }

        task.resume()

        BranchArray =
            [BranchTable(BranchTitle: ["FirstFirst","SecondFirst","ThirdFirst"]),
                BranchTable(BranchTitle: ["FirstSecond","SecondSecond","ThirdSecond"]),
                BranchTable(BranchTitle: ["FirstThird","SecondThird","ThirdThird"]),
                BranchTable(BranchTitle: ["FirstFourth"])]

        BranchLocationArray = [BranchLocation(BranchLocationValues: ["asdfasd","asdfasd","asdfas"]),
            BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
            BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"]),
            BranchLocation(BranchLocationValues: ["asdkljf","asdfasd","asdfas"])]

            // Reload the table
            self.tableView.reloadData()
            }

You need to call tableView.reloadData after you have updated the data structures. This has to be done in the main thread, thus:

 let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
     println(NSString(data: data, encoding: NSUTF8StringEncoding))
     var error: NSError?
     let jsonData: NSData = data /* get your json data */
     let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

     if let name: AnyObject = json["name"]  {
         for var index = 0; index < name.count; ++index {
             var Name : String  = name[index] as NSString
             self.branches.append(Branch(name: Name))
             println(Name)
         }
     }
     // NOTE: Calling reloadData in the main thread
     dispatch_async(dispatch_get_main_queue()) {
         self.tableView.reloadData()
     }
}

It seems, your data loading completes asynchronously, but you are reloading the table outside of the closure, so it might be executed before the load is completed. So, you can put the table reload inside the closure.

And also, the suggested queuing way is nice, you can have a read on GCD in apple doc:

dispatch_async(dispatch_get_main_queue()) { // Assign Job To The Main Queue }

dispatch_async Submits a block for asynchronous execution on a dispatch queue and returns immediately. It has two params - queue ; The queue on which to submit the block & block The job to submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM