dimanche 7 mai 2017

Load data from WebAPI to the ViewController

I would like to ask. my current code working perfectly it is for data load from web api to the ViewController (table view) . but i am confuse is violates the Dependency Inversion Principle(DIP) Of SOLID? If so, how to fix that?

class AreaController: UIViewController {

        var townCityList : [TownCity]?

        override func viewDidLoad() {
            super.viewDidLoad()

           // locations implements ILocation interface

            let service = NetworkModelTownCity()


            // So here, when creating a new instance you're injecting the dependecy.

            let dataprocess = DataProcessLocation(location : service)


            dataprocess.locations({ (locations) in

                 self.townCityList = locations
                 self.tableView.reloadData()
            })
        }

    }


protocol Ilocation {

    func townCitys(_ completionHandler: @escaping (_ locations: [TownCity]) -> Void)
}


class DataProcessLocation {

    var location : Ilocation!

    init(location : Ilocation) {

       self.location = location
    }

    func locations(_ completionHandler: @escaping (_ locations: [TownCity]) -> Void) {

        self.location.townCitys( { (locations) in

            completionHandler(locations)

        })

    }


}


class NetworkModelTownCity : Ilocation {


     func townCitys(_ completionHandler: @escaping ([TownCity]) -> Void) {

        let _jsonFormatString = ["":""]

        RestApiService.shared.fetchDataByPostRequest(with: _jsonFormatString  , actionMethod: Constants.ApiRequest.actionMethod.townCity.rawValue) { (json) in

            var  _objs = [TownCity]()

            print(json)

            guard let objList = json as? [AnyObject] else {
                return
            }

            for obj in objList {
                if  let _obj = TownCity(fromAPIResponse: obj as! Dictionary<String, AnyObject>){
                    _objs.append(_obj)
                }

            }


            completionHandler(_objs)

        }
    }

}

Aucun commentaire:

Enregistrer un commentaire