我正在尝试访问从我的API调用返回的JSON数据结构中的值。我只想在我的JSON中的shared
值为true时显示shared
图像,否则显示不同的图像。目前,当我启动应用程序时,前两个结果不显示图像,因为数据库中的值设置为false。但是当我向下滚动然后向上滚动时,它们会出现。我有点困惑如何使用JSON来检查条件。我是否在正确的位置检查每一行的条件?像SwitfyJSON这样的东西是更好的方法来访问我的嵌套JSON数据结构吗?
class FactsTableViewController: UITableViewController, UISearchBarDelegate {
var data = [AnyObject]()
var id = String()
func callAPI() {
let user = "user"
let pass = "pass"
let url = "https://example.com/api"
Alamofire.request(.GET, url, parameters: nil)
.authenticate(user: user, password: pass)
.responseJSON { (request, response, JSON, error) in
self.data = JSON! as [AnyObject]
self.tableView.reloadData()
self.cacheFacts()
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
let cell = tableView!.dequeueReusableCellWithIdentifier("facts", forIndexPath: indexPath!) as FactTableViewCell
cell.factTitle.text = data[indexPath!.row]["preferredPhrase"] as? String
cell.factBody.text = data[indexPath!.row]["content"] as? String
// If the value of teamShared is true show image, else show something different
if let shared = self.data[indexPath!.row]["shared"] as? Bool {
var isShared = UIImageView(frame: CGRectMake(10, 95, 15, 15)); // set as you want
var isSharedImage = UIImage(named: "team.png");
isShared.image = isSharedImage;
cell.addSubview(isShared);
// This always prints true even if the JSON is set to false. Can't figure out why this is?
println(shared)
}
return cell
}
}
答案 0 :(得分:0)
有两个问题,第一,你正在使用缓存的单元格,但没有清理它们。所以你应该在退货前进行清洁。 2,只要解包成功,if let就会返回true。所以你应该再次检查一下这个值。
注意:我没有测试代码,仅用于演示。
cell.viewWithTag(333)?.removeFromSuperview() // Find the tag and remove it.
if let shared = self.data[indexPath!.row]["shared"] as? Bool {
if shared {
var isShared = UIImageView(frame: CGRectMake(10, 95, 15, 15)); // set as you want
isShared.tag = 333 // Assign a tag to it
var isSharedImage = UIImage(named: "team.png");
isShared.image = isSharedImage;
cell.addSubview(isShared);
println(shared)
}
}