0

I have an issue bellow. I would like when I push on the refresh button to refresh the data contain in my UITable. So I have an alamofire function that do a GET to my server et the data is used for populate the table.

The issue is that the numberOfRowsInSection & cellForRowAt are called before the end of the call to the API.

I was maybe thinking to add a Bool the the func refreshData but I didn't success I tried also with

let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
dispatchGroup.leave()

but without success

    @IBAction func btnResetPressed(_ sender : UIButton?) {
        hud.textLabel.text = "Loading"
        hud.show(in: self.view)
        self.refreshData()
        hud.dismiss()

    }

    func refreshData() {
        AF().GETBon("\(appUrl.urlApiBonUnbilled)", success: { (response) in
            self.arrBonUnbilled.removeAll()
            var responseObjectBonUnbilled: ResponseObjectBonUnbilled?
            responseObjectBonUnbilled = try? JSONDecoder().decode(ResponseObjectBonUnbilled.self, from: response)
            self.arrBonUnbilled.append(contentsOf: responseObjectBonUnbilled!.data)

            if let data = try? PropertyListEncoder().encode(self.arrBonUnbilled) {
                UserDefaults.standard.setValue(data, forKey: "ListingBon")
                print (try! PropertyListDecoder().decode([BonUnbilled].self, from: UserDefaults.standard.data(forKey: "ListingBon")!))
            }
        }) { (Error) in
            print ("KO: \(Error)")
        }
    }

Thanks in advance for your help. If you have any suggestion also for improving the code they are welcome.

jo7332
  • 9
  • 2

2 Answers2

0

Reload the table view in refreshData() and move also the line to dismiss the hud into the closure

@IBAction func btnResetPressed(_ sender : UIButton?) {
    hud.textLabel.text = "Loading"
    hud.show(in: self.view)
    self.refreshData()
}

func refreshData() {
    AF().GETBon("\(appUrl.urlApiBonUnbilled)", success: { (response) in
        self.arrBonUnbilled.removeAll()
        var responseObjectBonUnbilled: ResponseObjectBonUnbilled?
        responseObjectBonUnbilled = try? JSONDecoder().decode(ResponseObjectBonUnbilled.self, from: response)
        self.arrBonUnbilled.append(contentsOf: responseObjectBonUnbilled!.data)
        self.tableView.reloadData()
        self.hud.dismiss()
        if let data = try? PropertyListEncoder().encode(self.arrBonUnbilled) {
            UserDefaults.standard.set(data, forKey: "ListingBon")
            print (try! PropertyListDecoder().decode([BonUnbilled].self, from: UserDefaults.standard.data(forKey: "ListingBon")!))
        }
    }) { (error) in
        print ("KO: \(error)")
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Thanks Vadian for the fast and correct answer thats solved the issue. I had to add also:

let Height : CGFloat = self.tblData.contentSize.height
self.tblData.frame.size.height = Height

for resize the table

jo7332
  • 9
  • 2