Quickly populate a table with json from url using Alamofire

Similar works, but the problem is that I believe the table is being created before alamofire can grab the json file. If I print self.dates after loading it displays fine. Is there a way to pause browsing while loading. Or am I taking a completely wrong approach here? Thanks to

import UIKit
import Alamofire

class TableViewController: UITableViewController {
var dates: [String] = []
var times: [String] = []

override func viewWillAppear(animated: Bool) {
    self.tableView.reloadData()
}

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

    loadPosts()
}

func loadPosts() {
    Alamofire.request(.GET, "http://localhost:5000/listposts")
        .responseSwiftyJSON {(request, response, jsonObj, error) in
            for index in 0...jsonObj.count-1 {
                self.dates.append(jsonObj[index]["appDate"].stringValue)
                self.times.append(jsonObj[index]["appTime"].stringValue)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView!.reloadData()
            })
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonPress() {
    self.tableView!.reloadData()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.dates.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = self.dates[indexPath.row]
    cell.detailTextLabel?.text = self.times[indexPath.row]
    return cell

}
}

      

+3


source to share





All Articles