SwiftUI: List API Call

Ronak Patel
2 min readJun 17, 2022

In this post we are going to take a look at how we can get JSON data from an API and show it in a list view in SwiftUI.

Let’s jump right in and get started by creating a new SwiftUI project.

Our expected output:

Step1: Create a UserDetails model class for fetching the user’s details.

import Foundation
class UserDetails : Codable , Identifiable{
let id : Int?
let name: String?
let email : String?
let gender : String?
let status : String?
init(id: Int,name: String,email: String,gender: String,status : String) {
self.id = id
self.name = name
self.email = email
self.gender = gender
self.status = status
}
}

Step2: Will create a service UserDetailsAPI class to call the API.

import Foundation

public enum RequestType: String {
case GET, POST, PUT,DELETE
}

class UserDetailsAPI {

func request() -> URLRequest {

var request = URLRequest(url:
URL(string:"https://gorest.co.in/public/v2/users")! )
request.httpMethod = RequestType.GET.rawValue
request.addValue("application/json", forHTTPHeaderField: "Accept")
return request
}

func getUsers(completion:@escaping ([UserDetails]) -> ()) {
URLSession.shared.dataTask(with: request()) { (data, _, _) in
let users = try! JSONDecoder().decode([UserDetails].self, from:
data!)
DispatchQueue.main.async {
completion(users)
}
}
.resume()
}
}

Step3: Create a UserListView swiftUI view to display the response.

import SwiftUI

struct UserListView: View {
@State var userDetails : [UserDetails] = []

var body: some View {
List(userDetails){ user in
HStack{
Text(user.name ?? "")
.fontWeight(.heavy)
Spacer()
if user.status == "active"{
Text(user.status ?? "")
.foregroundColor(Color.green)
}else{
Text(user.status ?? "")
.foregroundColor(Color.red)
}
}
}
.listStyle(.plain)
.onAppear{
//api call...
UserDetailsAPI().getUsers(completion: {
(users) in
self.userDetails = users
})
}
}
}
 struct UserListView_Previews: PreviewProvider {
static var previews: some View {
UserListView()
}
}

Thanks for reading this blog….

--

--