iosswiftuitableview

Data does not show up in table view cell when I run my code


Please help! I've tried everything. If anyone has any advice on how I can display my data in the table view cell, I would be eternally grateful. I'm new to iOS and am learning on a very steep pace. I grabbed data from an API that returned data in the form of JSON, parsed it, created my table view with its table view cells, but I can't seem to figure out how to print the data I parsed through in the table view cell.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  
    @IBOutlet weak var myTableView: UITableView! {
        didSet {
            myTableView.dataSource = self
            myTableView.delegate = self
        }
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = NSURL(string: "https://api.viacom.com/apiKey=someKey")!
        let request = NSMutableURLRequest(URL: url)
        
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request) { data, response, error in
            if let response = response, data = data {
                
                var json: [String: AnyObject]!
                do {
                    json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! [String : AnyObject]
                    } catch {
                            print(error)
                
                    }

        //2 - Store in model, forloop through them, store into temparray,add to main array?

        
                 let episodes = json["response"] as! [String: AnyObject]
                 let meta = episodes["episodes"] as! [AnyObject]
                 let description = meta[2]["description"]! as! String?
                 //let title = meta[2]["title"] as! String?
                 let episodeNumber = meta[2]["episodeNumber"]! as! String?
                
                 dispatch_async(dispatch_get_main_queue(), {
                     self.myTableView.reloadData()})
                
                data = [episodeNumber!, description!]
                
                
                print("Episode Number: \(episodeNumber!)\n" + "Description: \(description!)")
                
                } else {
                
                print(error)

                }
            }
        
        task.resume()
    }
    
    let data = [description]
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        cell.textLabel!.text = "\(self.data)"

        return cell
    }

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

}

Solution

  • The reason for the failure is too much of data manipulation. There is no need to use so many variables and pass around data unnecessarily. You are getting correct output in console when printing it because you used variables "episodeNumber" and "description".

    print("Episode Number: \(episodeNumber!)\n" + "Description: \(description!)")
    

    And getting wrong data in variable "data".

    So better thing would be that you should use episodeNumber and description variables to print data in Cell.

    cell.textLabel!.text = "Episode Number: \(self.episodeNumber)\n" + "Description: \(description)"
    

    But for this you have to make variable episodeNumber a global variable.

    So declare it outside the function.

    var episodeNumber = String()
    

    and remove the let keyword from line

    let episodeNumber = meta[2]["episodeNumber"]! as! String?
    

    You have to add some self. keywords which the compiler will suggest you so you don't have to worry about that, just keep on double clicking the suggestions.

    Now, your code looks fine to run and get desired output.