iOS Dev Course: JSON, Codable, NSURLSession & Repository
How to GET data from remote API? How to decode custom type from JSON data?
Let’s make a simple project with API Client in quick guide!
Create a new Single View App project.
Hotkey: shift + command + N
Let’s make API Client that GET data from remote API using Foundation.NSURLSession class.
But before a little part of theory.
What is URLSession?
URLSession class and related classes provide an API for downloading content. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app isn’t running or, in iOS, while your app is suspended.
URLSessionAPI involves many different classes working together in a fairly complex way that may not be obvious if you read the reference documentation by itself. Before using this API, you should read the overview in the URL Loading System topic. The articles in the First Steps section offer examples of performing common tasks with
Continue on Apple Developer
Create an APIClient.swift
Good! That is our core engine. Let’s implement it in ViewController.swift
- Create a resource with endpoint
- Load resource using apiClient
- Print result in console
Look at console output. Here is String data.
Let’s make it better and decode data to custom data type.
Codable Data Type
Many programming tasks involve sending data over a network connection, saving data to disk, or submitting data to APIs and services. These tasks often require data to be encoded and decoded to and from an intermediate format while the data is being transferred.
The Swift standard library defines a standardized approach to data encoding and decoding. You adopt this approach by implementing the
Decodable protocols on your custom types. Adopting these protocols lets implementations of the
Decoderprotocols take your data and encode or decode it to and from an external representation such as JSON or property list. To support both encoding and decoding, declare conformance to
Codable, which combines the
Decodable protocols. This process is known as making your types codable.
Continue on Apple Developer
- Create repository constant
- Get Flights Structure items using repository
Let’s check console output!
Nice! There are some FlightData items. Now we can work with data items into project.
Did you want to know How to extend Repository to work with Realm local database? -> read next Article Repository with Realm
You’ve done it! Clap! Clap!
Remember, the receipt to success is continuous learning and communication with colleagues including, self-education.
This was a small guide about URLSession, Codable protocol and Repository pattern. Read more on Apple Developer site. Don’t stop self-education.
Subscribe to my account to get notifications about new stories.
If you still have questions — write about it in the comments. I’ll answer them in future articles.