article

Monday, May 17, 2021

SwiftUI Fetch JSON data display into list and view details to another view

SwiftUI Fetch JSON data display into list and view details to another view


Learn how to create an API call to get data from a remote JSON file and display this data in a SwiftUI list

I used dropbox to host my json file url : https://dl.dropboxusercontent.com/s/1y7yqdefyayegzo/employeelist.json?dl=0
ContentView.swift
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct User: Decodable {
    let id: String
    let name: String
    let email: String
    let about: String
}

struct ContentView: View {
    @State var users = [User]()

    var body: some View {
        NavigationView {
            List{
                ForEach(users, id: \.id) { item in
                    NavigationLink(destination: details(item: item)) {
                        HStack {
                            //Image("user")
                                //.resizable()
                                //.frame(width: 50, height: 50)
                                //.clipShape(Circle())
                                //.overlay(Circle().stroke(Color.white, lineWidth: 4))
                            Text(item.name)
                                .font(.headline)
                            //Text(item.email)
                            //Text(item.about)
                        }.padding(7)
                    }
                }
            }
            .onAppear(perform: loadData)
            .navigationTitle("Navigation")
        }
    }

    func loadData() {
        guard let url = URL(string: "https://dl.dropboxusercontent.com/s/1y7yqdefyayegzo/employeelist.json?dl=0") else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) {data, response, error in
            if let data = data {
                //pull out the declaration of the decoder object
                let decoder = JSONDecoder()
                //set how we want to interpret dates in the JSON
                decoder.dateDecodingStrategy = .iso8601
                //decode directly to an array of User structs rather than a Response
                if let decodedResponse = try?
                    decoder.decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        //decodedResponse is now [User] rather than Response.User
                        self.users = decodedResponse
                    }
                    return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")

        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
details.swift
 
//
//  details.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct details: View {
    
    let item: User
    
    var body: some View {
        
        VStack {
            Image("user")
                .clipShape(Circle())
                .overlay(
                    Circle().stroke(Color.orange, lineWidth: 4)
                )
                .shadow(radius: 10)
            Text(item.name)
                .font(.title)
            Text(item.email)
                .font(.subheadline)
            
            Divider()
 
            Text(item.about)
                .font(.headline)
                .multilineTextAlignment(.center)
                .lineLimit(50)
        }.padding()
        
    }
}

Related Post