0

I have to put data in tableview, but even tough I get info from JSON, I can't pass data to postTitle variable. Why is that? Here is my code:

import UIKit

class ViewController: UIViewController, UITableViewDelegate,     UITableViewDataSource {

var postTitle = [AnyObject]()

override func viewDidLoad() {
    super.viewDidLoad()

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json"

    //        https://hacker-news.firebaseio.com/v0/item/9324191.json

    if let url = NSURL(string: baseURL) {
        var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

            if error != nil {
                println("Error: \(error.localizedDescription)")
            } else {
                var jsonError: NSError?
                if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSArray {

                        self.postTitle.append(topStories)

                }


            }

        })


        taskURL.resume()

    }


}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    println(postTitle.count)
    return postTitle.count
}



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

    println(self.postTitle)
  //  cell.textLabel?.text = postTitle[indexPath.row]
    return cell
}




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


}
2
  • What error do you see? Commented Apr 5, 2015 at 21:01
  • Are you aware that dataTaskWithURL() works asynchronously? – See for example stackoverflow.com/questions/28782932/…, or search for "get value from asynchronous function". Commented Apr 5, 2015 at 21:11

3 Answers 3

1

topStories is an NSArray, but you are appending it to the postTitle array (which is of type [AnyObject]). Array.append adds a single item to the array. So you will have added one entry, an NSArray of a bunch of post IDs, to your postTitle array.

I am guessing what you want is to add the contents of topStories to postTitle? In which case you want to use the extend rather than the append method:

self.postTitle.extend(topStories)
Sign up to request clarification or add additional context in comments.

2 Comments

Or use the += syntax: self.postTitle += topStories
The problem is that i have this function which return's me 0. And even if put what @Airspeed Velocity suggest. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { println(postTitle.count) return postTitle.count }
0

Given that you apparently reload ALL the titles with each request, you could just as easily do this: self.titles = topStories

I just built a test app this way and it worked perfectly fine.

PS: self.postTitle.append would have yielded the wrong result anyway, as it would also append titles you already have in your array. The method you probably should be using would be self.postTitle.join as it uses intersection.

5 Comments

It didn't work. Nothing is stored in postTitle variable, but if i println(self.postTitles) after JSONSerialization, it stored values in that variable. I don't get it.
i need to check it, i found other solution
Interested to know what your final solution is :-)
So the other guy from Reddit help me out. I was missing few things. First was data type Int, which needs to be passed to instance variable, and second was UITableView: here is working solution. Hope this will help someone. ``
0

So the other guy from Reddit help me out. I was missing few things. First was data type Int, which needs to be passed to instance variable, and second was UITableView: here is working solution. Hope this will help someone.

import UIKit

class ViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {

var postTitles = [Int]()

override func viewDidLoad() {
    super.viewDidLoad()

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json"


    if let url = NSURL(string: baseURL) {
        var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

            if error != nil {
                println("Error: \(error.localizedDescription)")
            } else {
                var jsonError: NSError?
                if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? [Int] {
                        self.postTitles = Array(topStories[0...9])

                        // Reload the table with our new results!
                        self.tableView.reloadData()
                }
            }

        })

        taskURL.resume()

    }
}

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

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


    let postTitle = String(self.postTitles[indexPath.row])

    cell.textLabel?.text = postTitle

    return cell
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.