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
try something like this approach:
MVVM architecture
I recommend using this approach.
(I wrote this without a compiler, so there may be errors, but the gist should be clear)