The purpose of this tutorial is to show a simple way to fetch data from a remote JSON file and display it on a List in SwiftUI. Apple has a tutorial with a local file, also this one teaches you how to do this, however I want to show a simpler way using a newer version of Xcode 11.0 (11A420a).
Apple beta libraries are getting constantly changed before releasing the final versions, so older tutorials might not work on the latest versions of XCode
Supposing we have this JSON file, that show an array of movie titles.
And we want to display them on a SwiftUI List like this.
First we need to define the model for Movie in this case a struct with Decodable and Identifiable protocols. Decodable to be able to decode it from the JSON file and Identifiable to be able to be listed with List. List allows you to display a list of data from an Identifiable Collection just like a UITableViewController.
CodingKeys basically maps the JSON key names with the variable name of the Model you created. In this case instead of year I named it released just for the purpose of showing that you can use your own names in the model as long as you define it in Coding Keys.
Next we create the fetcher class that will load the JSON file and decode it.
Before understanding what is happening, we need to understand the new Combine framework.
The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.
ObervableObject: A type of object with a publisher that emits before the object has changed. By default an
ObservableObject synthesizes an
objectWillChange publisher that emits the changed value before any of its
@Published properties changes.
@Published wraps the movies array and will generate events whenever it is changed.
The load() method fetches the JSON data from the network asynchronously, once the data has been loaded we assign it to movies. When movies changes it will send an event a subscriber.
This is the SwiftUI view, a List with the ObservedObject fetcher as parameter. Whenever movies is updated, the list will update autmatically.
The whole code is here.