我是 SwiftUI 的新手,想知道是否有人可以帮助我使我的应用程序正常工作。此外,我试图了解 MVVM,并想知道我是否做得正确。
该应用程序调用https://jsonplaceholder.typicode.com/users,我正在尝试根据 json 响应生成用户卡。
模型:
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]
看法:
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)
}
}
视图模型:
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()
}
}
我想在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()
}
}
}
我的问题是没有显示单个 UserView,因为传递给 UserView 的用户数组是空的。有人可以告诉我我做错了什么吗?我对此没有扎实的把握。谢谢。