2016-02-19 18 views
8

Tôi có mã sau đây.Điền các ô xem bảng từ JSON với Alamofire (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 
    } 
} 

Các ô bảng không được cập nhật mặc dù tôi đã bao gồm hàm self.tableView.reloadData() trong hàm hoàn thành yêu cầu Alamofire. Tôi cũng đã định nghĩa một đối tượng mẫu có tiêu đề và tất cả các thuộc tính được đặt thành "TEST", điều này được tải, tuy nhiên tệp JSON không điền bảng. Tôi có thể thấy tập tin đang được tải xuống một cách chính xác và đọc, nhưng tôi nghĩ rằng các yếu tố hoặc là không được thêm vào biến bất động sản happyHours hoặc bằng cách nào đó các yếu tố không được tải lại.

Tôi đã thử nhiều giải pháp từ đây nhưng không thành công. Tôi đang làm gì sai?

Trả lời

11

Đường dây self.tableView.reloadData() của bạn nằm ngoài gọi lại, có nghĩa là nó được gọi ngay lập tức, trước khi dữ liệu được tải. Hãy thử điều này:

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! Cảm ơn, đã làm việc như một say mê. –

+1

@ RinorBytyçi Không có vấn đề gì, một sai lầm dễ mắc phải! :) Btw, hãy thử sử dụng [Alamofire-SwiftyJSON] (https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) để giảm bớt việc xử lý phản hồi JSON. – Tometoyou

Các vấn đề liên quan