我正在尝试从 API 获取数据并将其显示在 tableView 中。
因为从我的应用程序中多次使用的 API 获取数据。所以我想让它可重用。
我创建一个名为 GetProducts
的类来从 API 获取数据,并将其保存到 Posts
class GetProducts{
static var products = [Product]()
static func loadProducts( _ filter: [String:String]) {
// get data from API
// append products to products list
}
}
在viewController中,我想从GetProducts
类中获取产品数据,并将其显示在tableView中
class MainViewController: UIViewController,UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
GetPeoducts.loadProducts([...])
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GetProducts.products.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as ProductTableViewCell
cell.products = GetProducts.products
return cell
}
}
但是,在 tableView 中,products
列表为空。
我无法弄清楚哪一步是错误的。有谁能帮我理清逻辑吗?
提前致谢!
最佳答案
基本上,我正在做的是使用完成处理程序
class GetPosts{
static var products = [Product]()
static func loadProducts( _ filter: [String:String], completion:(([Product]) -> Void)?) {
// get data from API
// append products to products list
completion?(self.products)
}
}
在ViewController中调用loadPoducts
:
class MainViewController: UIViewController,UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
var products = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
GetPeoducts.loadProducts(/*some params*/){ (products) in
self.products = products
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.products.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as ProductTableViewCell
cell.products = self.products
return cell
}
}
谢谢! @rmaddy @Vanya @Aakash @Jelord Rey
关于ios - Swift 如何重构从 API 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613646/