I'm trying to show data in UITablleView
after getting it from an HTTP request. I heard that the best and professional way to do it is configure the cell and do the call request in model class then send it to the view controller.
Here is what I tried to do, but I think it's not going well. I know this is a wrong way but I wanted to show you what I got based on someone.
UITable View Cell
@IBOutlet weak var status : UILabel!
@IBOutlet weak var date : UILabel!
@IBOutlet weak var model : UILabel!
func ConfigCell (car : Car){
let urlstr = "http://localhost:8000/api/newuser/check"
let url = URL(string: urlstr)
guard let token = UserDataSingleton.sharedDataContainer.token else { return }
let headers = ["Authorization":"Bearer \(token)"]
var statusCode: Int = 0
request(url! , method: .get, encoding: JSONEncoding.prettyPrinted , headers: headers )
.responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
let json = JSON(value)
for (key, subJson) in json["allcar"] {
if let status = subJson["status"].string {
self.status.text = status
if let date = subJson["created_at"].string {
self.date.text = date
if let model = subJson["model"].string {
self.model.text = model
let Status = [
Car(model: model, status: status, date: date)]
Car model
class Car {
private var _mode : String?
private var _status : String?
private var _date : String?
var model : String{
return _model!
}
var status : String {
return _status!
}
var date : String {
return _date!
}
init(model : String , status :String,date : String) {
self._status = status
self._model = model
self._date = date
}
Controller
class testViewController: UIViewController, UITableViewDelegate , UITableViewDataSource {
let data = [Car]()
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
tableview.delegate = self
tableview.dataSource = self
print(data.count)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CarCell",for: indexPath) as! CarC
let entry = data[indexPath.row]
cell.date.text = entry.date
cell.model.text = entry.model
cell.status.text = entry.status
return cell