2016-02-19 89 views
8

我有以下代碼。使用Alamofire從JSON填充tableview單元格(Swift 2)

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()。我還定義了一個帶有標題的樣本對象,並將所有屬性設置爲「測試」,這會得到加載,但JSON文件不會填充表格。我可以看到文件正在被正確下載並讀取,但我認爲這些元素要麼未被添加到屬性變量happyHours,要麼未被重新加載。

我從這裏嘗試了很多解決方案,但沒有成功。我究竟做錯了什麼?

回答

11

您的self.tableView.reloadData()行位於回調之外,這意味着它在數據加載之前立即被調用。試試這個:

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)") 
      } 
    } 
} 
+1

Lifesaver!謝謝,這就像一個魅力。 –

+1

@RinorBytyçi沒有問題,一個容易犯的錯誤! :)順便說一句,嘗試使用[Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON)來緩解JSON響應的處理。 – Tometoyou