从API调用中填充tableView中的单元格

时间:2017-04-26 03:06:33

标签: ios swift uitableview

我被迫使用异步调用(我想在swift中关闭)来使用SDK(APIWrapper)获取我需要的数据。在我能够获得我需要的数据之前,我发现该视图正在被初始化。

所以我的第一个问题是,如何在视图加载之前让我的单元格将表格视图中需要的数据引入?那么,为什么我想在此时使用异步调用

import APIWrapper
import UIKit

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let provider = APIWrapper
    var categories = [String]()


    //define number of cells
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        categories = []
        self.getCells()
        print("count " , self.categories.count)
        return(self.categories.count)
    }

    //get number of cells
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "categories")
        cell.textLabel?.text = categories[indexPath.row]
        return(cell)
    }

    private func getCells(){
        provider?.getCategoriesWithCallback { (response, error) -> () in
            if error == nil {
                print("response ", response)
                self.updateTableViewWithCategories(categories: response as! [APIWrapperCategory])
            }
            else {
                print("FUCKK")
            }
        }
    }

    private func updateTableViewWithCategories(categories: [APIWrapperCategory]){
        for category in categories{
             print("category obj " , category)
             print("category name " , category.name)
        }
    }
}

我的控制台的输出看起来像

count  0
count  0
count  0
count  0
response  Optional([<APIWrapperCategory: 0x6000002a0300>])
category obj  <ZDKHelpCenterCategory: 0x6000002a0300>
category name  General
response  Optional([<ZDKHelpCenterCategory: 0x6180002a30c0>])
category obj  <ZDKHelpCenterCategory: 0x6180002a30c0>
category name  General
response  Optional([<ZDKHelpCenterCategory: 0x6180002a30c0>])
category obj  <ZDKHelpCenterCategory: 0x6180002a30c0>
category name  General
response  Optional([<ZDKHelpCenterCategory: 0x6180002a3300>])
category obj  <ZDKHelpCenterCategory: 0x6180002a3300>
category name  General

2 个答案:

答案 0 :(得分:2)

您正在从tableview的数据源方法获取表视图的数据。

要从API调用中获取数据,请在视图控制器的self.getCells()方法中调用viewDidLoad()方法,如下所示:

override func viewDidLoad() {
      //your code here
      //get cells data    
      self.getCells()
 }

将您的api响应数据添加到表视图数据源:

  private func updateTableViewWithCategories(categories: [APIWrapperCategory]){
    self. categories = []
    for category in categories{
         print("category obj " , category)
         print("category name " , category.name)
         self. categories.append(category.name)
    }
    //reload table view here
    DispatchQueue.main.async {
         self.yourTableView.reloadData()
    }
 }

并将委托方法更改为:

  //define number of cells
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("count " , self.categories.count)
    return(self.categories.count)
}

答案 1 :(得分:0)

所以我最终使用viewWillAppear并改变了返回数据的方式以使单元格填充,所以这里是代码,我希望这可以帮助其他人

@IBOutlet weak var tableView: UITableView!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.getCategoriesFromZendesk()
}


//define number of cells
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("count " , self.categories.count)
    return self.categories.count
}

//get number of cells
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //Add Label to the Prototype Cell
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "categories")
    cell.textLabel?.text = categories[indexPath.row]    
    return(cell)
}


private func getCategories(){

    self.categories = []

    provider?.getCategoriesWithCallback { (response, error) -> () in
        if error == nil {
            print("response ", response?.map{($0 as AnyObject as? APIWrapperCategory)?.name ?? ""} ?? "empty")
            self.updateTableViewWithCategories(categories: response as? [APIWrapperCategory])
        }
        else {
            print("FUCKK")
        }
    }
}


private func updateTableViewWithCategories(categories: [APIWrapperCategory]?){
    self.categories = categories?.flatMap{$0.name} ?? []
    tableView.reloadData()
}