获取JSON数据以从Array填充TableView

时间:2016-05-26 18:37:54

标签: arrays json swift uitableview

我能够在循环中使用我的JSON数据成功填充数组,并且我正在尝试使用相同的信息填充TableView的单元格,但是目前列表中没有内容。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var table: UITableView!

    var headlines = [String]()
    let baseURL = "http://api.nytimes.com/svc/topstories/v1/business.json?api-key=123456789"



    override func viewDidLoad() {
        getJSON()
        super.viewDidLoad()
        self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.table.dataSource = self
        self.table.delegate = self
    }

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


    func getJSON() {

        let url = NSURL(string: baseURL)
        let request = NSURLRequest(URL: url!)
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in

            if error == nil {
                let SwiftyJSON = JSON(data: data!)
                let theTitle = SwiftyJSON["results"].arrayValue

                for title in theTitle{

                    let titles = title["title"].stringValue
                    self.headlines.insert(titles, atIndex: 0)
                    //print("- " + titles)
                }

                print(self.headlines)

            }

            else {
                print("there was an error")
            }
        }

        task.resume()

    }


    // From the UITAbleViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return headlines.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
        cell.textLabel!.text = self.headlines[indexPath.row]
        return cell
    }

    // From the UITableViewDelegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped on cell # \(indexPath.row)")
    }
}

1 个答案:

答案 0 :(得分:0)

任务是异步的,所以当你加载数组时,你必须重新加载表

func getJSON() {

    let url = NSURL(string: baseURL)
    let request = NSURLRequest(URL: url!)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in

        if error == nil {
            let SwiftyJSON = JSON(data: data!)
            let theTitle = SwiftyJSON["results"].arrayValue

            for title in theTitle{

                let titles = title["title"].stringValue
                self.headlines.insert(titles, atIndex: 0)
                //print("- " + titles)
            }

            print(self.headlines)
            self.table.reloadData()
        }

        else {
            print("there was an error")
        }
    }

    task.resume()

}