I'm new to SwiftUI, and was wondering if someone could help me make my app work. Also I'm trying to get my head around MVVM, and was wondering if I was doing it correctly.
The app makes a call to https://jsonplaceholder.typicode.com/users and I'm trying to generate user cards based on the json response.
Model:
import Foundation
// MARK: - User
class User: Codable {
let id: Int
let name, username, email: String
let address: Address
let phone, website: String
let company: Company
init(id: Int, name: String, username: String, email: String, address: Address, phone: String, website: String, company: Company) {
self.id = id
self.name = name
self.username = username
self.email = email
self.address = address
self.phone = phone
self.website = website
self.company = company
}
}
// MARK: - Address
class Address: Codable {
let street, suite, city, zipcode: String
let geo: Geo
init(street: String, suite: String, city: String, zipcode: String, geo: Geo) {
self.street = street
self.suite = suite
self.city = city
self.zipcode = zipcode
self.geo = geo
}
}
// MARK: - Geo
class Geo: Codable {
let lat, lng: String
init(lat: String, lng: String) {
self.lat = lat
self.lng = lng
}
}
// MARK: - Company
class Company: Codable {
let name, catchPhrase, bs: String
init(name: String, catchPhrase: String, bs: String) {
self.name = name
self.catchPhrase = catchPhrase
self.bs = bs
}
}
typealias Users = [User]
View:
import SwiftUI
struct UserView: View {
let user: User
var body: some View {
VStack {
Text(user.name)
.font(.title)
.fontWeight(.bold)
Text(user.email)
.font(.callout)
.foregroundColor(.gray)
.textCase(.uppercase)
}
.frame(width: 300, height: 200, alignment: .center)
.background(Color.yellow)
.cornerRadius(10.0)
}
}
ViewModel:
import SwiftUI
class UserViewModel: ObservableObject {
@Published var users: Users = []
init() {
fetchUsers()
}
func fetchUsers() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { print("Invalid url")
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else {
print("There was an error: \(String(describing: error?.localizedDescription))")
return
}
do {
let userData = try JSONDecoder().decode(Users.self, from: data)
print("success: \(userData.capacity)")
} catch let parsingError {
print("There was an error: \(parsingError.localizedDescription)")
}
}
task.resume()
}
}
And I want to display it in a UserContainerView:
struct UserContainer: View {
let uservm = UserViewModel()
var body: some View {
VStack {
Button(action: uservm.fetchUsers, label: {
Text("Fetch some users boy")
})
ForEach(uservm.users, id: \.id, content: { user in
UserView(user: user)
})
Spacer()
}
}
}
My problem is not a single UserView is displayed, because the array of Users passed to UserView is empty. Can someone tell me what am I doing wrong? I don't have a solid grasp on this. Thanks.
You need to have view model as observed, like
struct UserContainer: View {
@ObservedObject var uservm = UserViewModel()
and assign parsed users, like
do {
let userData = try JSONDecoder().decode(Users.self, from: data)
print("success: \(userData.capacity)")
DispatchQueue.main.async { [weak self] in
self?.users = userData // make sure if correct type here - cannot test
}
} catch let parsingError {