ios – 使用Alamofire(Swift 2)从JSON填充tableview单元格

我有以下代码.
import UIKit
import Alamofire

class CheHappyTableViewController: UITableViewController,NSURLConnectionDelegate {

    var happyHours = [HappyHour]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Load the cell elements
        loadHappyHourElements()
    }

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

    func loadHappyHourElements(){

        let testhappyhour:HappyHour = HappyHour(title: "TEST",image: "TEsst",description: "TEST",postedDate: "TEST")
        self.happyHours.append(testhappyhour)

        let url:String = "https://gist.githubusercontent.com/arianitp/036133ebb5af317a595c/raw/f134ec241ec3126bedd6debe5de371e3e01d225b/happyhours.json"
        Alamofire.request(.GET,url,encoding:.JSON).responseJSON
            { response in switch response.result {
            case .Success(let JSON):
                let response = JSON as! NSArray
                for item in response { // loop through data items
                    let obj = item as! NSDictionary
                    let happyhour = HappyHour(title:obj["title"] as! String,image:obj["image"] as! String,description:obj["description"] as! String,postedDate:obj["date"] as! String)
                    self.happyHours.append(happyhour)
                }

            case .Failure(let error):
                print("Request Failed with error: \(error)")
                }
        }
        self.tableView.reloadData()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation,return the number of sections
        return 1
    }

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

    //displays the cells in the table
    override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        self.tableView.rowHeight = UIScreen.mainScreen().bounds.size.width
        let cellIdentifier = "CheHappyTableViewCellController"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier,forIndexPath: indexPath) as! CheHappyTableViewCellController

        let happyHour = happyHours[indexPath.row]
        cell.lblTitle.text = happyHour.title
        //cell.cheHappyImage = happyHour.photo

        // Configure the cell...
        return cell
    }
}

即使我在Alamofire请求完成函数中包含self.tableView.reloadData(),表单元格也不会更新.我还定义了一个带有标题的示例对象,并且所有属性都设置为“TEST”,这确实被加载,但是JSON文件没有填充表格.我可以看到文件正在正确下载并读取,但我认为元素要么没有被添加属性变量happyHours,要么以某种方式没有重新加载元素.

我从这里尝试了很多解决方案但没有成功.我究竟做错了什么?

解决方法

你的self.tableView.reloadData()行在回调之外,这意味着在加载数据之前它会被立即调用.试试这个:
func loadHappyHourElements(){

    let testhappyhour:HappyHour = HappyHour(title: "TEST",postedDate: "TEST")
    self.happyHours.append(testhappyhour)

    let url:String = "https://gist.githubusercontent.com/arianitp/036133ebb5af317a595c/raw/f134ec241ec3126bedd6debe5de371e3e01d225b/happyhours.json"
    Alamofire.request(.GET,encoding:.JSON).responseJSON
        { response in switch response.result {
        case .Success(let JSON):
            let response = JSON as! NSArray
            for item in response { // loop through data items
                let obj = item as! NSDictionary
                let happyhour = HappyHour(title:obj["title"] as! String,postedDate:obj["date"] as! String)
                self.happyHours.append(happyhour)
            }
            self.tableView.reloadData()

        case .Failure(let error):
            print("Request Failed with error: \(error)")
            }
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...