2014-11-08 4 views
0

내 API 호출에서 반환되는 JSON 데이터 구조 내의 값에 액세스하려고합니다. 내 shared 이미지는 내 JSON 값이 shared 인 경우에만 표시하고 그렇지 않으면 다른 이미지를 표시하고 싶습니다. 현재 앱을 실행하면 데이터베이스에서 값이 false로 설정되기 때문에 처음 두 결과는 이미지를 표시하지 않습니다. 그러나 아래로 스크롤 한 다음 다시 스크롤하면 나타납니다. JSON을 사용하여 조건부를 검사하는 방법을 조금 혼란스럽게 생각합니다. 올바른 위치의 각 행에 대한 조건부를 확인하고 있습니까? 내 중첩 JSON 데이터 구조에 액세스하려면 SwitfyJSON과 같은 것이 더 나은 방법일까요?Swift 및 Alamofire - 조건문에 대한 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

언제나 사실을 인쇄하는 경우 왜 처음부터 이미지가 보이지 않습니까? – Shuo

답변

0

두 가지 문제가있다, 첫째, 당신은 캐시 된 셀을 사용하고 있지만, 그것들을 정리하지 않았다. 따라서 반환하기 전에 청소를해야합니다. 둘째, if let은 unwrap이 성공하는 한 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) 
     } 
    } 
+0

어떻게 할 수 있습니까? 검색을 몇 번했는데 해결책을 찾을 수없는 것 같습니다. 이것이 일반적인 패턴이라면 이것이 문서화되어야한다고 생각하겠습니까? –

관련 문제