【发布时间】:2016-06-20 20:35:08
【问题描述】:
我正在尝试使用 Alamofire 获得的响应填充我的 UITableView。 JSON 的 URL 是 https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed。我只需要这个 JSON 中的 response.result.value["results"] 字典数组。 我没有问题,但是当我尝试在 Alamofire 之外打印它时,请求为空,并且我的单元格无法填充此数据,因为单元格数为 0。 我在主线程中尝试了 tableView.reloadData(),正如这里所说的 Populating Table Cells With Alamofire Data,但这没有产生积极的结果。你认为我做错了什么?我委托了表格视图并更新了框架,一切都应该正常工作。
这里是一段代码:
func retrieveRecentEntries() {
let url = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed"
Alamofire.request(.GET, url, parameters: [:], encoding: .JSON, headers: [:]).responseJSON { (response) in
self.entries = (response.result.value!["results"] as? [NSDictionary])!
dispatch_async(dispatch_get_main_queue()) {
print("OO")
print("Entries1: \(self.entries)")//giving JSON
self.tableView.reloadData()
}
}
print("Entries2: \(self.entries)")//empty
}
UITableView 委托方法:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Sort entries by date and return amount of entries for each date section
return entries.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("entryCell", forIndexPath: indexPath) as! EntryCell
//Populate each indexPath.row with one entry
let entryDict = entries[indexPath.row]
let dateString = entryDict["release_date"] as! String
formatter.dateFormat = "yyyy-MM-dd"
let dateDate = formatter.dateFromString(dateString)
formatter.dateFormat = "MMMM d, yyyy"
let dateStr = formatter.stringFromDate(dateDate!)
//Store entry details to show them as labels
let projectName = entryDict["title"] as! String
let description = entryDict["overview"] as! String
let task = entryDict["original_title"] as! String
let hours = entryDict["vote_average"] as! Double
//Show cell labels
cell.projectNameLabel.text = projectName
cell.dateLabel.text = dateStr
cell.taskLabel.text = task
cell.descriptionLabel.text = description
cell.hoursLabel.text = String(format: "%.2f", hours)
print("HERE")//this isn't printed
return cell
}
【问题讨论】: