skip to Main Content

I am new to swift coding, I am trying to fetch data from API and was able to print data in the console as per below format after doing changes in model file.

Result(
    customerList: [
        walletApp.ResultItem(
            accountId: "00000023880",
            card: "5120"
        ),
        walletApp.ResultItem(
            accountId: "3880",
            card: "581"
        ),
        walletApp.ResultItem(
            accountId: "3881",
            card: "750"
        )
    ]
)

Below is my viewmodel code

import Foundation

class apiCall {
    func getUsers(completion:@escaping ([Result]) -> ()) {
        
        let url = URL(string: "http://myapi-call-ges-here")!
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"

        URLSession.shared.dataTask(with: request) { (data, response , error) in
     
            do{
                let result = try JSONDecoder().decode(Result.self,from: data!)
                print(result)
                
            }
            catch{
                print("Error:(error)")
            }
         }.resume()
        }
}

Below is my STRUCT code

import SwiftUI

struct Result: Codable {
    let customerList:[ResultItem]
    
}

struct ResultItem:Codable{
    let accountId: String
    let card:String
}

Below is my VIEW page where i need to display accountId and card in a LIST

import SwiftUI

struct successLogin: View {
    @State var users: [Result] = []
    var body: some View {
        Text("USERS LIST")
            .bold()
            .font(.largeTitle)
            .underline()
//        List(users){ user in
//
//            Text(Result)
//                .font(.headline)
//            Text(Result)
//                .font(.subheadline)
//        }
            
            .onAppear{
                apiCall().getUsers{(users) in self.users = users
                    
                }
            }
           //.padding()
    }
}

in the commented LIST code, what changes do i need to make to display data of card and accountId

2

Answers


  1. try something like this approach:

    struct successLogin: View {
        @State var users: [ResultItem] = []  // <-- here
        var body: some View {
            Text("USERS LIST")
                .bold()
                .font(.largeTitle)
                .underline()
            
            List(users){ user in
                Text(user.accountId)  // <-- here
                    .font(.headline)
                Text(user.card)       // <-- here
                    .font(.subheadline)
            }
            .onAppear{
                ApiCall().getUsers { users in
                    self.users = users
                    
                }
            }
            //.padding()
        }
    }
    
    struct Result: Codable {
        let customerList:[ResultItem]
    }
    
    struct ResultItem: Codable, Identifiable { // <-- here
        let id = UUID()  // <-- here
        let accountId: String
        let card:String
    }
    
    class ApiCall {
        
        func getUsers(completion:@escaping ([ResultItem]) -> ()) { // <-- here
            
            let url = URL(string: "http://myapi-call-ges-here")!
            var request = URLRequest(url: url)
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.httpMethod = "GET"
            
            URLSession.shared.dataTask(with: request) { (data, response , error) in
                // guard for data, todo
                do {
                    let result = try JSONDecoder().decode(Result.self,from: data!)
                    print(result)
                    completion(result.customerList) // <-- here
                } catch {
                    print("Error:(error)")
                    completion([]) // <-- here
                }
            }.resume()
        }
    }
    
    Login or Signup to reply.
  2. MVVM architecture

    // ViewModel
    final class SuccessLoginViewModel: ObservableObject {
       @Published var users: Result = .init(customerList: [])
    
       func getUsers() {
            
            let url = URL(string: "http://myapi-call-ges-here")!
            var request = URLRequest(url: url)
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.httpMethod = "GET"
    
            URLSession.shared.dataTask(with: request) { (data, response , error) in
         
                do{
                    let result = try JSONDecoder().decode(Result.self, from: data!)
                    self.users = result
                    
                }
                catch{
                    print("Error:(error)")
                }
             }.resume()
            }
    }
    
    // SwiftUI View
    struct successLogin: View {
        @ObservedObject model
    
        var body: some View {
            Text("USERS LIST")
                .bold()
                .font(.largeTitle)
                .underline()
            List(model.users.customerList) { user in
                Text(user.accountId)
                   .font(.headline)
                Text(user.card)
                    .font(.subheadline)
            }
                .onAppear{
                    model.getUsers()
                }
        }
    } 
    
    

    I recommend using this approach.

    (I wrote this without a compiler, so there may be errors, but the gist should be clear)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search