刷新UITableViewController数据

时间:2017-11-22 05:18:27

标签: ios swift api uitableview

我有2个控制器, DashboardController LocateVehicleController 。 LocateVehicleController有 UITableViewController

在DashboardController中,按下按钮,我正在进行API调用并获取数据。并将数组发送到LocateVehicleController。

 let locateVehicleStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
 let locateVehicleController = locateVehicleStoryboard.instantiateViewController(withIdentifier: "tempID") as? LocateVehicle
 self.present(locateVehicleController!, animated: true, completion: nil)
 locateVehicleController?.dataArray = self.locateVehicleDataArr
 locateVehicleController?.tableView.reloadData()

在LocateVehicleController中我有刷新按钮,如果我按下刷新按钮,我需要更新我使用过来自DashboardController的API调用数据的tableview控制器数据。

根据我的理解,当我按下刷新按钮时,将调用相同的API调用。请帮忙解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我会将调用此API的逻辑移到另一个类。将此类注入DashboardControllerLocateVehicleController并使用它来获取数据。像这样:

struct Vehicle {
}

protocol VehicleDataFetcherProtocol {
    func getVehicleData(completionHandler:([Vehicle])->()) // assuming the data is in form of an Array of a class/struct Vehicle
}

class VehicleDataFetcher: VehicleDataFetcherProtocol {
    // Hit API, get data and call the completion  hanlder
    func getVehicleData(completionHandler:([Vehicle])->()) {

    }
}

class DashboardController:UIViewController {
    private var vehicleDataFetcher: VehicleDataFetcher!

    func injectVehicleDataFetcher(dataFetcher:VehicleDataFetcher) {
        self.vehicleDataFetcher = dataFetcher
    }

    func presentLocateVehicle() {
        let locateVehicleStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let locateVehicleController = locateVehicleStoryboard.instantiateViewController(withIdentifier: "tempID") as? LocateVehicleController
        self.present(locateVehicleController!, animated: true, completion: nil)
        locateVehicleController?.injectVehicleDataFetcher(dataFetcher: self.vehicleDataFetcher)
        locateVehicleController?.dataArray = self.locateVehicleDataArr
        locateVehicleController?.tableView.reloadData()
    }
}

class LocateVehicleController:UIViewController {
    private var vehicleDataFetcher: VehicleDataFetcher!

    func injectVehicleDataFetcher(dataFetcher:VehicleDataFetcher) {
        self.vehicleDataFetcher = dataFetcher
    }


}