1

我是 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 的用户数组是空的。有人可以告诉我我做错了什么吗?我对此没有扎实的把握。谢谢。

4

2 回答 2

1

您需要观察到的视图模型,例如

struct UserContainer: View {
    @ObservedObject var uservm = UserViewModel()

并分配解析的用户,例如

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 {
于 2021-01-04T07:22:47.657 回答
1

(拿起@Asperi 遗漏的地方,因为他/她的回答将解决您的问题)

根据您的代码,这部分看起来可能会给您带来麻烦

  import SwiftUI

class UserViewModel: ObservableObject {
    @Published var users: Users = []
      ...
    }

而是应该

   import SwiftUI

class UserViewModel: ObservableObject {
    @Published var users: [User] = []
    }

并且要添加到先前的答案,因为建议是直接投射它,self?.users = userData所以应该进行一项调整:

let userData = try JSONDecoder().decode([Users].self, from: data)

唯一的变化是您将其解码为一个数组,因为这是您选择发布者在 viewModel 中的内容。

于 2021-01-04T11:23:56.697 回答