如何将 JSON 响应放入 tableview

How to put JSON response to a tableview

我有一个模型 Users 并且在该模型中

    static func getUsers() -> Single<[Users]> {
    let path = API.Path.users.details
    let params: [String: Any] = [
        "utcOffset": TimeZone.current.utcOffset
    ]

    return API.requestMany(path: path, method: .get, parameters: params)
    }

我是这样声明的

    let sus = [Users]()

在我的 cellForRowAt 我有这个

        Users
        .getUsers()
        .do(onError: { [weak self] error in
            print(error.localizedDescription)
        })
        .do(onSuccess: { [weak self] userNames in
            print(userNames)
            cell.name.text = userNames[indexPath.row].name
        })
        .subscribe()
        .disposed(by: rx.disposeBag)

该代码没有被调用,所以我的表视图是空的,但是当我尝试将它放入 ViewDidLoad 时,它被调用并触发了我的打印语句 print(userNames )

你的代码没有被调用,因为没有任何东西在调用你放入代码的函数。它在 viewDidLoad 中工作,因为正在调用该函数。

根据您的描述,我希望您的 viewDidLoad() 中的代码看起来像这样

    Users.getUsers()
        .asObservable()
        .bind(to: tableView.rx.items) { tableView, index, user in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath(index: index)) as! MyTableViewCell
            cell.configure(for: user)
            return cell
        }
        .disposed(by: disposeBag)

根据您的评论,我了解到您只想使用 Rx 进行网络调用。在这种情况下,解决方案应如下所示:

final class ExampleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    private var users: [User] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self

        _ = User.getUsers()
            .subscribe(
                onSuccess: { [weak self] in
                    self?.users = [=11=]
                    self?.tableView.reloadData()
                },
                onError: { error in
                    print("handle network error here")
                }
            )
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        users.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyTableViewCell
        cell.configure(for: users[indexPath.row])
        return cell
    }
}

final class MyTableViewCell: UITableViewCell {
    func configure(for user: User) { 
        print("configure your cell here")
    }

}

struct User {
    static func getUsers() -> Single<[User]> { fatalError("Implement me") }
}