Jack Daniel Jack Daniel - 29 days ago 21
iOS Question

Data not load to UITableView with Alamofire + SwiftyJSON

In my iOS app I'm using Alamofire for rest request and SwiftyJSON for parsing. the rest url is working and I get all data from server, I print it in console. but I can't populate that data with UITableView. I get no errors, project compiles and runs without any issue, but the table view is empty. this is my simple code:

var contracts = [Contract]()

override func viewDidLoad() {
super.viewDidLoad()

getContracts(contractSearchCriteria: ContractSearchCriteria())

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 0
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (contracts.count != 0) {
return contracts.count
}
return 0
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contractCell", for: indexPath)

let contract = self.contracts[indexPath.row]

cell.textLabel?.text = contract.insuredPersonFullName
cell.detailTextLabel?.text = contract.companyName

return cell
}


this is getContracts method:

func getContracts(contractSearchCriteria : ContractSearchCriteria) {
let params : Parameters = ["insuredPersonName": contractSearchCriteria.insuredPersonName]

Alamofire.request("\(Constants.restURL)getContracts", method: .post, parameters: params, encoding: JSONEncoding.default).validate().responseJSON(completionHandler: {response in

switch (response.result) {
case .success(let value):
let json = JSON(value)
let result = Result(json: json)
print(result.isSuccess)

for data in json["data"].arrayValue {
print(data)
self.contracts.append(Contract(json: data))
}
self.tableView.reloadData()
case .failure(let error):
print(error)
}


})

}


I use swift 3, and latest Alamofire with SwiftyJSON in Xcode 8. what is wrong in my code? I can't find any solution.

Answer
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
Comments