从 API 调用生成视图 - SwiftUI

Generating views from API call - SwiftUI

我是 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)
    }
}

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()
        
    }
}

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

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

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 {

(在@Asperi 因为 his/her 的回答而遗漏的地方拾取将解决你的问题)

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

  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 中选择的发布者。