0

I'm populating my tableView with JSON data, most of the time the data shows but for some strange reason other times it doesn't. I tested the JSON data in Chrome and the info is there. I also made print statements to print the info after it has downloaded and it appears to download correctly. I can't figure out why 80% of the time the data populates the tableView correctly and 20% of the time it doesn't. Here is a sample of my code, there are many more cells but I shortened it to 2 for this example:

    var task : NSURLSessionTask?
    var newURL : String? 
    var bannerArray: [String] = []
    var overViewArray: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    getJSON(newURL!)

  }

      func getJSON (urlString: String) {

        let url = NSURL(string: urlString)!
        let session = NSURLSession.sharedSession()
        task = session.dataTaskWithURL(url) {(data, response, error) in
          dispatch_async(dispatch_get_main_queue()) {
            if (error == nil) {
              self.updateDetailShowInfo(data)
            }
            else {
              "Not getting JSON"
            }
          }
        }
        task!.resume()
      }


     func updateDetailShowInfo (data: NSData!) {
        do {
          let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

          guard let banner = jsonResult["banner"] as? String,
          let overview = jsonResult["overview"] as? String 
          else { return }
          _ = ""

          print(overview)

          bannerArray.append(banner)
          overViewArray.append(overview)
     }
        catch {
          print("It ain't working")
        }
        self.DetailTvTableView.reloadData()
        }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
      }

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

        switch section {
        case 0: return bannerArray.count
        case 1: return overViewArray.count
        default: fatalError("Unknown Selection")
        }
      }

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

        switch indexPath.section {

        case 0:
          let cell = tableView.dequeueReusableCellWithIdentifier("bannerCell", forIndexPath: indexPath) as! BannerCell
          cell.bannerImage.sd_setImageWithURL(NSURL(string: bannerArray[indexPath.row]))
          self.DetailTvTableView.rowHeight = 100
          DetailTvTableView.allowsSelection = false
          return cell

        case 1:
          let cell = tableView.dequeueReusableCellWithIdentifier("overviewCell", forIndexPath: indexPath) as! OverviewCell
          let overViewText = overViewArray[indexPath.row]
          if overViewText != "" {
            cell.overView.text = overViewText
          } else {
            cell.overView.text = "N/A"
          }
          self.DetailTvTableView.rowHeight = 200

          print(overViewArray[indexPath.row])
          return cell

     default: ""
        }
        return cell
      }
tylerD
  • 53
  • 10
  • Can you define "not working?" Which sections of that code do or don't run when it works vs. when it doesn't? – thislooksfun Feb 16 '16 at 00:35
  • The tableView doesn't seem to be presenting the JSON data. It doesn't show any cell at all. What's strange is that it only does it sometimes, most of the time it works. – tylerD Feb 16 '16 at 00:44
  • So it's still _loading_ the JSON, it's just not displaying it? Namely, `updateDetailShowInfo` is both still being called and working properly? – thislooksfun Feb 16 '16 at 00:51
  • Yes, that appears to be the case although for some strange reason the self.DetailTvTableView.reloadData() doesn't always get called. – tylerD Feb 16 '16 at 00:55
  • There are a couple of code paths where reloadData wouldn't be called. For example, maybe your `guard` is failing or the JSON error is not nil. Have you stepped through the code to see which way it's going? – Michael Feb 16 '16 at 01:50

1 Answers1

2

I'm just doing this off the web. And I think there are some errors. You need to debug them yourself.

Your understanding of fetching the JSON and GCD is totally wrong. I believe these codes you got somewhere off the web. Go read up what is dispatch_async.

Basically, you need to create session to fetch JSON data, which you have done it correctly, however, within the NSJSONSerialization, you need to store them in a variable and append it to your array. This is fetched asynchronously. Your dispatch_async will reload data serially.

func getJSON (urlString: String) {
    let url = NSURL(string: urlString)!
    let session = NSURLSession.sharedSession()
    task = session.dataTaskWithURL(url) {(data, response, error) in
    let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        guard let banner = jsonResult["banner"] as? String,
        let overview = jsonResult["overview"] as? String 

        bannerArray.append(banner)
        overViewArray.append(overview)
     } dispatch_async(dispatch_get_main_queue()) {
            if (error == nil) {
              self.DetailTvTableView.reloadData()
            }
            else {
              "Not getting JSON"
            }
          }
    catch {
        print("It ain't working")
            }

            }
        }
        task!.resume()
}
jo3birdtalk
  • 616
  • 5
  • 20
  • The code example works a bit better, one of the cells that wasn't populating data now does. Although when I make a breakpoint at the self.DetailTVTableView.reloadData() point it shows that all but one of my arrays are empty even though the JSON data downloaded correctly. Any idea why this might be happening? – tylerD Feb 16 '16 at 18:51
  • which array is that? Did you place it within the NSJSONSerialization? – jo3birdtalk Feb 17 '16 at 03:30
  • It wound up working after appending the array immediately after the json data downloaded before downloading the next piece of json data. Why some I can batch download and append while others won't work unless downloaded and appended individually is strange. – tylerD Feb 17 '16 at 20:57