2017-01-20 1 views
-1

json 배열의 일부 데이터가 표시되지만 json 배열 길이의 셀 수만큼 정확하게 전체 배열을 인쇄합니다. 특정 데이터를 표시하려면 어떻게해야합니까? 여기 swson을 사용하여 json 배열에서 특정 요소를 선택하십시오. 3

내 JSON 링크입니다 :

class PhotosByAlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { 

@IBOutlet weak var myCollectionView: UICollectionView! 

var albumId:Int = 1 // It is my album ID 
var allImages: [Any] = [] 
let urlForData = URL(string: "https://jsonplaceholder.typicode.com/photos") 

override func viewDidLoad() { 
    super.viewDidLoad() 


    callToFetchJson() 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func callToFetchJson() { 

    let request = URLRequest(url: urlForData!) 
    URLSession.shared.dataTask(with: request) { (data, response, error) in 
     if data == nil && error != nil { 
      print("No Data") 
     } 
     else if data != nil && error != nil { 
      print("Error") 
     } 
     else { 
      DispatchQueue.main.sync { 
       self.decodingJson(data!) 
      } 

     } 
     }.resume() 
} 


func decodingJson(_ data: Data) { 
    do { 
     let allImage = data 
     allImages = try JSONSerialization.jsonObject(with: allImage, options: JSONSerialization.ReadingOptions.allowFragments) as! [Any] 
     self.myCollectionView.reloadData() 
    } 
    catch { 

    } 

} 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 

    return CGSize(width: 150 , height: 180) 

} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return self.allImages.count 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "albumPhotoCell", for: indexPath as IndexPath) as! albumPhotoCollectionViewCell 

    let aImg:[String: AnyObject] = allImages[indexPath.item] as! [String: AnyObject] 
    cell.imageDescription.text = (aImg["title"] as! String) 
    return cell 
} 

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    // handle tap events 
    print("You selected cell #\(indexPath.item)!") 

} 
} 
+0

JSON 링크를 살펴본 결과로드하는 데 10 초 정도 걸립니다. JSON의 작은 샘플을 며칠 만에 죽을지도 모르는 링크를 제공하는 대신 질문으로 옮길 수 있습니까? – akousmata

+0

@akousmata 인터넷 연결 속도가 느린 것 같습니다. 남자를 개선하십시오 –

+0

그것은 죽지 않을 것입니다. 나는이 링크를 가짜 json api로 발견했다. 이 링크는 json 데이터를 사용하여 모든 제품을 테스트하기위한 것입니다. –

답변

2

당신은 당신의 배열을 필터링해야 : 그 데이터의 제목을 표시 할 https://jsonplaceholder.typicode.com/photos

ALBUMID은 = 여기

1 내 코드입니다 deserialization 후. 이 충분해야한다 :

func decodingJson(_ data: Data) { 
    do { 
     let allImage = data 
     allImages = try JSONSerialization.jsonObject(with: allImage, options: JSONSerialization.ReadingOptions.allowFragments) as! [Any] 
     allImages = allImages.filter { $0["albumId"] == albumId } 
     self.myCollectionView.reloadData() 
    } 
    catch { 

    } 

} 

이 줄을 추가 한 후, "albumId" : 1 만 요소는 당신의 allImages 배열에 포함되어야한다.

+0

내 솔루션을 찾았습니다. URL에서이 작업을 수행 할 수 있습니다. urlForData (URL : "https://jsonplaceholder.typicode.com/photos?albumId=\(albumId)") in viewdidload –

+0

By your way –

+0

문제 없어요! 귀하의 API가 그러한 querry를 지원했다는 것을 알고 있다면 그것을 제안했을 것입니다. 일반적으로 백엔드에 많은 비즈니스 로직/무거운 작업을 제공하는 것이 가장 좋습니다. – Losiowaty

관련 문제