使用Alamofire(Swift 2)从JSON填充tableview单元格 [英] Populating tableview cells from JSON with Alamofire (Swift 2)

查看:113
本文介绍了使用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 ,要么以某种方式没有重新加载元素。

The table cells don't get updated even though I included the self.tableView.reloadData() in the Alamofire request complete function. I have defined also one Sample Object with Title and all Properties set to "TEST", this does get loaded, however the JSON file doesn't populate the table. I can see the file is being downloaded correctly and read, but I think the elements are either not being added to the Property Variable happyHours or somehow the elements are not being reloaded.

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

I tried many solutions from here but without success. What am I doing wrong?

推荐答案

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

Your self.tableView.reloadData() line is outside the callback, meaning that it gets called straight away, before the data has been loaded. Try this:

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)
            }
            self.tableView.reloadData()

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

这篇关于使用Alamofire(Swift 2)从JSON填充tableview单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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