Home > database >  Swift - How to create Array list to fill the TableView from API data
Swift - How to create Array list to fill the TableView from API data

Time:11-22

Hey guys good morning :) , how can I make it to fill the data fetched from API to TableView, so I can learn it once and for all.

So the data come from API in that form shown below and I just need some guidance to make the data available in every cell of my tableview.these are the cells that needs to be filled

let token = "NjQzODM2N0NDNDM4NDhCNDFSA3jA0QUY0NjVEFF="

static let shared = APICaller()
private let baseURL = "http://111.111.111.111:3030/api/"

private init() {}

func getVehicles(for id: String, completed: @escaping (Result<[Vehicles],Errors>) -> Void ){
    let endpoint = baseURL   "GetVehicles?UserIdentificationValue=\(id)"
    
    
    guard let url = URL(string: endpoint) else {
        completed(.failure(.invalidURL))
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "GET"


    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("Bearer \(token)",   forHTTPHeaderField: "Authorization")
    
    
    let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            
            if let _ = error {
                completed(.failure(.unableToComplete))
                return
            }
            guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
                completed(.failure(.invalidResponse))
                return
            }
            guard let data = data else {
                completed(.failure(.invalidData))
                return
            }
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .useDefaultKeys

                let vehicles = try decoder.decode([Vehicles].self, from: data)
                completed(.success(vehicles))
                
            } catch let error {
                completed(.failure(.invalidData))
            }
        }
        task.resume()

    }

This is the structure data that I must fill in table view:

struct Vehicles: Codable {

var  IDVehicle: Int?
var  Title: String?
var  RegistrationDate: String?
var  ExpireDate: String?
var  Department: String?
var  Identification: String?
var  Speed: String?
var  Latitude: Double?
var  Longitude: Double?
var  Angle: Int?
var  Status: Int?
var  InputValue: Int?
var  Plate: String?
var  LastCommunicationDate: String?
var  Passengers: Int?
var  Driver: String?

}

CodePudding user response:

In Your TableViewController Class

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var listOfVechicle = [Vehicles]()
    override func viewDidLoad() {
        super.viewDidLoad()
        //Fetch Data From Backend
        fetchDataFromAPI()
    }
    
    func fetchDataFromAPI(){
        
        let id = "1"
        DispatchQueue.global().async {
            APIManager.shared.getVehicles(for: id) { Result in
                switch Result{
                case.success(let vechicles):
                    self.listOfVechicle = vechicles
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    print("error")
                }
            }
        }
        
    }

extension ViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listOfVechicle.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? CustomTableViewCell else {return UITableViewCell()}
        //You can Access Your Vehicles Model Values Here one by one
        var currentVechicle = listOfVechicle[indexPath.row]
        cell.expiryDateLable.text = currentVechicle.ExpireDate
        return cell 
    }
}

CodePudding user response:

I am using MVVM architecture. and with this method I print my data to the screen. If you are asking for the code part, you can print the service you created example model struct yourModal: Codable { var KM: Double } like this:

     var RandomName: [yourModal]!
     var api: String = ""
     var token: String = ""

     Service().YourServiceName(api: self.api, token: self.token) { blnc in
               if let blnc = blnc {
               self.RiskBalan = blnc
               self.Yourlabel.text = self.RandomName[0].KM
    }
  • Related