【发布时间】:2017-01-20 13:21:29
【问题描述】:
我正在显示 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)!")
}
}
【问题讨论】:
-
我查看了您的 JSON 链接,加载大约需要 10 秒。您能否将该 JSON 的一小部分样本移到问题中,而不是提供一个可能在几天后失效的链接?
-
@akousmata 我认为您的 Internet 连接速度很慢。改善男人
-
它不会死的。我发现这个链接是假的 json api。这些链接可用于使用 json 数据测试任何产品。