JSON and collection views

No idea how to load JSON content into a Collectionview, there is no video tutorial for this ?

Playing around with other samples from tableviews but not getting anywhere… Any advice would be helpful.

Trying to load a image, then text from a remote server, all the tutorials have the images stored within the app itself…?

@dringer Thanks very much for your question!

The first thing you need to understand when parsing JSON from the server is that you’ll need to connect to a REST API from your app using Apple’s URLSession API. Assuming you don’t need any help with the networking portion, then I would STRONGLY recommend that you learn how to use the “Codable” protocol which was just recently introduced in Swift 4. A good starting point would be to go through the following article.

In a nutshell, create a struct class which implements the Codable protocol, and model it after the JSON data that you are receiving from your REST API. Then using your networking code, decode the data object that you receive from the cloud into an array of these struct model objects, and then pass it back to the class which is the DataSource for your UICollectionView, and then iterate through the array and display the contents. :slight_smile:

I hope this helps!

All the best!

Hi David (@dringer),
A quick short answer to your question.

Do you know how to use a collection view? If you do using it from JSON data is no different, the only additional step involved is downloading the JSON data and converting it into the data structure (dataSource) that runs the collection view.

So the question is what are you looking for,

  • loading JSON?
  • converting JSON to a structure
  • using a CollectionView?

cheers,

Hi

Thanks for the assistance, I am a absolute beginner, and perhaps trying to run before I can walk…

I’ve managed to follow another tutorial related to Flickr (Utilising TableViews) and got this to work with Collectionviews. So all sorted, I am now playing with dynamically resizing cells based on a string values within the array, for example News articles should be inserted at the top of the array, and cells made bigger and bolder so they stand out, not there yet though. Guessing I would use insertItems(at:)? Although how would I restructure the array to accommodate maybe multiple important news items, which should be shown first ?

I’ve sorted the issue of inserting items at the top - This appears to work…

if imgTitle.contains(“Breaking News”){
self.collectionData.insert(flickrImage.title, at: 0)
} else {
self.collectionData.append(flickrImage.title)
}

Thanks

This topic was automatically closed after 166 days. New replies are no longer allowed.