IOS/Swift rendering table after JSON request

I am new to IOS and swift. I am trying to implement an api get request that returns json and then display it in a table. Below is my current code. When I run simulator I am getting the following error:

fatal error: Cannot index empty buffer

If I remove the hardcoded return 3 in the tableView function and instead use doDatItems.count nothing renders in the table because I guess the array of doDatItems starts empty before the get request is made. It seems like a timing thing? How do I ensure the get request is made before the table loads?

import UIKit

class ViewController: UIViewController, UITableViewDelegate {

    var doDatItems:[String] = []

    @IBOutlet weak var doDatItem: UITextField!

    @IBOutlet weak var yourDoDats: UILabel!

    @IBAction func addDoDat(sender: AnyObject) {

        doDatItems.append(doDatItem.text)

        println(doDatItems)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        let urlPath = "http://localhost:3000/dodats"
        let url: NSURL = NSURL(string: urlPath)!
        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            println("Task completed")
            if((error) != nil) {
                // If there is an error in the web request, print it to the console
                println(error.localizedDescription)
            }
            var err: NSError?
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
            if(err != nil) {
                // If there is an error parsing JSON, print it to the console
                println("JSON Error \(err!.localizedDescription)")
            } else {
                let dataArray = jsonResult["dodats"] as [String]

                for item in dataArray {
                  self.doDatItems.append(item)
                }

//                println(self.doDatItems)

            }

        })

        task.resume()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 3

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        println(self.doDatItems)

        cell.textLabel?.text = self.doDatItems[indexPath.row]

        return cell
    }


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


}

Answers


I found several problems -

  1. You ViewController should conform to UITableViewDatasource (which is missing, not sure how it went that far)

  2. Do not return 3 when self.doDatItems does not have any items. It will cause a crash. As long as the data loads let the table remain empty. return self.doDatItems.count

  3. Once data is loaded and ready to display from self.doDatItems array, just call reloadData() method of your table view.

  4. Before that, you should have a reference (or IBOutlet) of your tableView so that you can call reloadData() from anywhere.


Need Your Help

Stepping into .Net framework4.6 source VS 2013

c# debugging visual-studio-2013 pdb-files .net-4.6

I am trying to step into the .Net source code. I have followed the instruction here, the "Microsoft symbol server" is unchecked and I have specified the symbol cache directory. In the module window...

Adding movie clips with for loop action script 3

actionscript-3

Hey wondering if anybody can help me, i am trying to add a load of move clips and make them clickable to the stage in action script 3,i can work out the spacing of them later i just keep getting er...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.