Populating tableview cells from JSON with Alamofire (Swift 2)

后端 未结 1 1650
耶瑟儿~
耶瑟儿~ 2021-01-05 00:12

I have the following code.

import UIKit
import Alamofire

class CheHappyTableViewController: UITableViewController,         


        
相关标签:
1条回答
  • 2021-01-05 00:49

    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)")
                }
        }
    }
    
    0 讨论(0)
提交回复
热议问题