VeeArr
VeeArr

Reputation: 31

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.
    }

}

Upvotes: -1

Views: 105

Answers (3)

Jay Mehta
Jay Mehta

Reputation: 1801

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.

Upvotes: 0

vikingosegundo
vikingosegundo

Reputation: 52237

let data = [description]

is a short form of

let data = [self.description]

and self.description() is the viewController's description method used for printing debug description. That is why

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

gives you [(Function)], as you just created an array with a stored function in it.

Upvotes: 0

jo3birdtalk
jo3birdtalk

Reputation: 616

Your codes look very messy to me. However, I'm just assuming that you have successfully fetched the JSON data. Fetching data is asynchronous. You therefore need to add a dispatch code inside. After your this line of code:

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

Add this

dispatch_async(dispatch_get_main_queue(), {
       self.tableView.reloadData()})

EDIT:

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

Upvotes: 1

Related Questions