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)!")
}
}
JSON 링크를 살펴본 결과로드하는 데 10 초 정도 걸립니다. JSON의 작은 샘플을 며칠 만에 죽을지도 모르는 링크를 제공하는 대신 질문으로 옮길 수 있습니까? – akousmata
@akousmata 인터넷 연결 속도가 느린 것 같습니다. 남자를 개선하십시오 –
그것은 죽지 않을 것입니다. 나는이 링크를 가짜 json api로 발견했다. 이 링크는 json 데이터를 사용하여 모든 제품을 테스트하기위한 것입니다. –