【问题标题】:Swift and Alamofire - Accessing JSON value for a conditional statementSwift 和 Alamofire - 访问条件语句的 JSON 值
【发布时间】:2014-11-08 14:24:36
【问题描述】:

我正在尝试访问从我的 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
}

}

【问题讨论】:

  • 如果总是打印出来,那为什么你一开始看不到图像?

标签: json swift alamofire


【解决方案1】:

有两个问题,第一个,您正在使用缓存的单元格但没有清理它们。因此,您应该在退货之前进行清洁。 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)
        }
    }

【讨论】:

  • 你能举例说明如何做到这一点吗?我已经进行了一些搜索,但似乎找不到解决方案。如果这是一种常见模式,我认为应该记录下来?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多