使用swift 3从json数组中选择特定元素

时间:2017-01-20 13:21:30

标签: ios json swift3

我正在显示json数组中的一些数据,但它正在打印整个数组,正好创建了json数组长度的单元格数。我想显示具体的数据然后我该怎么做?

这是我的json链接:     https://jsonplaceholder.typicode.com/photos

我想显示其albumId = 1

的数据的标题

这是我的代码:

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)!")

}
}

1 个答案:

答案 0 :(得分:2)

反序列化后需要过滤数组。这应该足够了:

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数组中。