2016-10-27 2 views
0

특정 키를 기반으로 JSON의 데이터로 테이블 뷰를 채우는 방법을 알고 있지만 데이터를 놓는 방법을 알아 내려고합니다. 키 - 값 쌍에 특정 값이있는 경우 테이블보기로 이동합니다. "위치":Swift : JSON 파일에 특정 값이있는 데이터로 TableView 채우기

특히, 내 JSON 파일은 키 - 값 쌍은 보유 "시카고", "대륙": "미국"

가 내 테이블보기의 위치를 ​​표시 할 "US"의 대륙 값을 가진 엔트리 중에서 다른 대륙을 가진 위치를 표시하고 싶지는 않습니다.

내가 얻을 수있는 도움을 주시면 감사하겠습니다. 여기에 내 parseJSON 파일에있는 것이 있지만 현재 내가하고 싶은 일을하지 않습니다. 나는

func parseJSON(){ 
    do{ 
     let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!) 

     let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) 

     for anItem in jsonResult as! [Dictionary<String, AnyObject>]{ 

      let mifiContinent = anItem["continent"] as! String! 
      if var mifiContinent = jsonResult["US"]{ 
       let mifiLocation = anItem["location"] as! String 
       let newLocation = Location(location: mifiLocation) 
       locationOfMifi.append(newLocation) 
      } 
     } 
    } 
    catch let error as NSError{ 
     print(error.debugDescription) 
    } 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    if let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath)as? LocationCell{ 

     let location: Location! 

     location = locationOfMifi[indexPath.row] 
     cell.configureCell(location) 
     return cell 

    } else{ 
     return UITableViewCell() 
    } 

} 
+0

당신은 가능성이 cellForRowAtIndexPath'은 어떻게 든 테이블 데이터 소스와 잘못 정렬 된'에 사용하고 당신의'locationOfMifi'array 때문에 범위 부족 오류가 있어요. 'numberOfRowsInSection' 메소드도 보여줄 수 있습니까? – Frankie

+0

이것은 CoreData의 완벽한 작업처럼 들립니다. 관심 분야에 해당하는 모든 속성을 갖는 데이터 모델을 작성해야합니다. 당신의 경우에는 대륙이 될 것입니다. 그런 다음 CoreData에게 북미를 대륙으로 갖는 모든 것을 가져 오라고 말할 수 있습니다. 배열 대신 CoreData를 사용하면 코드에 놀라운 일을 할 수 있습니다. –

답변

0

그냥

let mifiContinent = anItem["continent"] as! String! 
if mifiContinent == "US" { 
    let mifiLocation = anItem["location"] as! String 
    let newLocation = Location(location: mifiLocation) 
    locationOfMifi.append(newLocation) 
} 
0

당신은 또한 당신이있어 무엇을 함께하는 데 도움이되는 몇 가지 빠른 틱 구문을 시도 할 수 있습니다 필터링에 약간의 변경의 tableview 기능의 범위를 벗어난 배열 인덱스를 얻을 하기. 셀 구성을 약간 수정해야합니다.

struct Location { 
    var location: String? 
    var continent: String? 

    init(_ jsonResult: [String : AnyObject]) { 
     self.location = jsonResult["location"] as? String 
     self.continent = jsonResult["continent"] as? String 
    } 
} 

//defined in your class 
var locationOfMifi = [Location]() 

//where parsing your json result 
if let jsonResult = jsonResult as? [[String : AnyObject]] { 
    locationOfMifi = jsonResult.map({ Location($0) }).filter({ $0.continent == "US" }) 
} 

//your tableview datasource 
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return locationOfMifi.count 
} 
관련 문제