LocateVehicleController

LocateVehicleController

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

在DashboardController中,按On按钮可以进行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调用。请帮助解决此问题。提前致谢。

最佳答案

我会将调用此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
    }


}

09-26 08:47