从JSON获取数据并在UITableView上显示

时间:2015-11-12 07:36:35

标签: arrays swift2

我在线获取JSON数据并将其转换为NSArray,并将其转换为String和类Arrays来管理数据。但是,出于某种原因,代码会在行componentscan

之后退出GetData()方法

我还确认提取数据没有问题,但它无法在桌面上显示。

我还为download附加了我的项目文件。

来自ViewController.swift的代码

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

来自NameManager.swift的代码

import UIKit

class ViewController: UIViewController, UITableViewDataSource {
var nameList = [NameManager]()

    @IBOutlet weak var NameTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        GetData()
        // Do any additional setup after loading the view, typically from a nib.
        NameTable.dataSource = self
        NameTable.reloadData()
    }

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

    func GetData(){
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2")!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if let error = error {
                print(error)
            }
            if let data = data{
                do{
                    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                    let resultArray = resultJSON as? NSArray
                    for jsonObjectString in resultArray!{
                        let code = jsonObjectString["code"] as! String
                        let name = jsonObjectString["name"] as! String
                        let description = jsonObjectString["description"] as! String
                        self.nameList.append(NameManager(code: code, name: name, description: description))
                    }
                    self.nameList.count

                }catch _{
                    print("Received not-well-formatted JSON")
                }

            }
            if let response = response {
                let httpResponse = response as! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")
            }

        })
        task.resume()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        let count = nameList.count
        return count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let myCell = NameTable.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        myCell.textLabel?.text = nameList[indexPath.row].name
        myCell.detailTextLabel?.text = nameList[indexPath.row].description

        return myCell
    }

}

1 个答案:

答案 0 :(得分:3)

session.dataTaskWithRequest是异步的,并在后台线程中自动执行。

dataTaskWithRequest在看到task.resume()并在后台开始执行时启动。

因此,您的程序不会等待其完成并开始执行其后的指令。在您的示例中,您的代码将开始执行

    NameTable.dataSource = self
    NameTable.reloadData()

遵循GetData()方法。后台执行完成后,将执行完成处理程序中的代码。所以你的tableView没有刷新。

您可以通过不同的方式解决此问题。 一种方法是在完成处理程序中包含NameTable.reloadData()。另一种方法是在后台执行完成时从ViewController中删除。

希望它有所帮助。

编辑:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {
var nameList = [NameManager]()

    @IBOutlet weak var NameTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        NameTable.dataSource = self
        GetData()
        // Do any additional setup after loading the view, typically from a nib.

        //NameTable.reloadData()
    }

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

    func GetData(){
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.json-generator.com/api/json/get/bPfifKWNaq?indent=2")!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if let error = error {
                print(error)
            }
            if let data = data{
                do{
                    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                    let resultArray = resultJSON as? NSArray
                    for jsonObjectString in resultArray!{
                        let code = jsonObjectString["code"] as! String
                        let name = jsonObjectString["name"] as! String
                        let description = jsonObjectString["description"] as! String
                        self.nameList.append(NameManager(code: code, name: name, description: description))
                    }
                    self.nameList.count
                    dispatch_async(dispatch_get_main_queue(), {
                        self.NameTable.reloadData()
                    })
                }catch _{
                    print("Received not-well-formatted JSON")
                }

            }
            if let response = response {
                let httpResponse = response as! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")
            }

        })
        task.resume()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        let count = nameList.count
        return count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let myCell = NameTable.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        myCell.textLabel?.text = nameList[indexPath.row].name
        myCell.detailTextLabel?.text = nameList[indexPath.row].description

        return myCell
    }

}