ios - Swift 如何重构从 API 获取数据?

标签 ios swift

我正在尝试从 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/

相关文章:

swift - iOS - 将字符串转换为 double

ios - 你如何在 ios 中创建无限滚动轮播?

iOS 开发 : Using a custom image for the user annotation in MapBox

ios - 类似类型: Cannot specialize a non-generic definition

ios - 如何访问 PFObject 中的信息?

ios - CAPS 页面菜单 : willMoveToPage delegate method getting error

ios - 如何创建动态图像

ios - Swift:单击后退按钮后错过标签栏

ios - 乘以随机数并打印结果

ios - 为什么我在 Swift 中遇到 fatal error ?解包可选值时意外发现 nil