Swift Combine Network Call with Codable Supports

KD Knowledge Diet
2 min readMar 25, 2023

--

In the world of modern application development, network operations play a crucial role in making an application functional. In iOS development, Swift and the Combine framework can be utilized to perform networking operations with ease. This article will provide an overview of how to create a post model, which represents the data that is being fetched from the network, and also delve into the process of decoding network responses by utilizing Swift programming language.

Creating a Post Model

The first step in our networking operation is to create a post model. A post model is a struct that represents the data we want to fetch from the network. In our case, we want to fetch an array of posts, so we need to create a struct that represents a single post.

struct Post: Codable {
let title: String
let body: String
}

The Codable protocol allows us to easily encode and decode our struct to and from JSON. In our Post struct, we have two properties: title and body. These properties represent the data we want to fetch from the network.

Decoding Network Responses

Now that we have our post model, we need to fetch the data from the network and decode it into our Post struct. To do this, we can use the URLSession and the Combine framework.

let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: [Post].self, decoder: JSONDecoder())
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &cancellables)

In the code above, we create a URL object that represents the endpoint we want to fetch data from. We then create a dataTaskPublisher using URLSession.shared. The dataTaskPublisher fetches the data from the endpoint and publishes it to the pipeline.

Next, we use the map operator to extract the data from the published element. We then use the decode operator to decode the data into an array of Post structs. Finally, we use the sink operator to receive the values or errors produced by the pipeline.

Conclusion

In this article, we learned how to create a post model and decode network responses using Swift and the Combine framework. With these tools, we can easily fetch data from the network and use it in our iOS applications.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!