在Swift中,从JSON加载的tableView数据仅加载80%的时间 [英] In Swift, tableView data loaded from JSON only loads 80% of the time

查看:96
本文介绍了在Swift中,从JSON加载的tableView数据仅加载80%的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,我会用JSON数据填充tableView,但出于某些奇怪的原因,有时却没有.我在Chrome中测试了JSON数据,并且信息在那里.我还做出了打印声明,以在信息下载后将其打印出来,并且看来可以正确下载.我无法弄清楚为什么80%的数据正确地填充tableView而20%的时间没有正确填充.这是我的代码示例,还有更多的单元格,但在本示例中,我将其缩短为2:

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
      }

推荐答案

我只是在网络上这样做.而且我认为有一些错误.您需要自己调试它们.

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

您对获取JSON和GCD的理解是完全错误的.我相信您可以在网上找到这些代码.去读一下什么是dispatch_async.

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.

基本上,您需要创建会话来获取正确完成的JSON数据,但是,在NSJSONSerialization中,您需要将其存储在变量中并将其附加到数组中.这是异步获取的.您的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()
}

这篇关于在Swift中,从JSON加载的tableView数据仅加载80%的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆