将JSON解析为TableView

时间:2015-10-18 16:19:56

标签: ios json swift uitableview

我试图将我的JSON响应解析为我的TableView。问题是我在TableView中没有得到任何结果。

import UIKit
import Alamofire
import SwiftyJSON

class MenuViewController: UITableViewController {

    var products: [Product] = []

    // MARK: View Controller Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, Urls.menu).responseJSON { request in
            if let json = request.result.value {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                    let data = JSON(json)
                    var product: [Product] = []

                    for (_, subJson): (String, JSON) in data {
                        product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
                    }

                    dispatch_async(dispatch_get_main_queue()) {
                        self.products += product
                        self.tableView.reloadData()
                    }
                }
            }
        }
    }

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

    // MARK: - UITableViewDataSource

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.products.count
    }

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

    private struct Storyboard {
        static let CellReuseIdentifier = "Product"
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath)
        let product = self.products[indexPath.row]

        cell.textLabel?.text = product.name
        cell.detailTextLabel?.text = product.description

        return cell
    }

我调试了我的numberOfSectionsInTableView,得到了这个结果:

0
0
0
0
0
0
5

五是我的JSON请求中的项目总数,但我的视图永远不会更新。我正在观看一些关于Swift的课程,其中一个课程中,我看到老师展示了这种方法self.tableView.reloadData()但是对我来说没有用,或者至少,我做错了。< / p>

其余的代码,我认为是正确的,但没有重新加载数据,我无法在我的tableView中显示它。

谢谢。

2 个答案:

答案 0 :(得分:1)

你已将numberOfRowsInSection与numberOfSections混为一谈。为numberOfSections返回1(或者只删除该函数,它是可选的)和products.count for numberOfRows。

答案 1 :(得分:1)

您混淆了numberOfRowsInSectionoverride func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.products.count }

class Location: Object {
    dynamic var long: Double = 0
    dynamic var lat: Double = 0
}