2016-02-19 12 views
8

Ho il seguente codice.Popolamento di celle tableview di JSON con 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 
    } 
} 

Le celle della tabella non vengono aggiornati, anche se ho inserito il self.tableView.reloadData() nella richiesta completa funzione Alamofire. Ho definito anche un oggetto campione con titolo e tutte le proprietà impostate su "TEST", questo viene caricato, tuttavia il file JSON non popola la tabella. Posso vedere il file è stato scaricato correttamente e letto, ma penso che gli elementi non vengono aggiunti alla variabile di proprietà happyHours o in qualche modo gli elementi non vengono ricaricati.

Ho provato molte soluzioni da qui ma senza successo. Che cosa sto facendo di sbagliato?

risposta

11

La linea self.tableView.reloadData() non rientra nella richiamata, ovvero viene richiamata immediatamente, prima che i dati siano stati caricati. Prova questo:

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! Grazie, ha funzionato come un fascino. –

+1

@ RinorBytyçi Nessun problema, un errore facile da fare! :) Btw, prova a utilizzare [Alamofire-SwiftyJSON] (https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) per facilitare la gestione della risposta JSON. – Tometoyou

Problemi correlati