Reputation: 3745
In my application I have a requirement to get the response before loading the tableview. I need to call around 20 API's at same time. And each API data need to show each 1 cell in tableview.
I need to call them in Viewdidload method which calls before tableview methods.
Can anyone guide or provide some useful example to do this?
Upvotes: 1
Views: 407
Reputation: 3918
You should use dispatch groups like this:
let group = DispatchGroup()
group.enter()
networkCall1 {
// response received
group.leave()
}
group.enter()
networkCall2 {
// response received
group.leave()
}
group.notify(queue: DispatchQueue.main, execute: {
// this will be notified only when there is no one left in the group
})
Before a network call you enter a group. When you receive a response you leave the group and when there is no one left in the group, group.notify
block will execute.
This is just a simple explanation, you should read more about it to fully understand how it works.
Upvotes: 1
Reputation: 5945
My suggestion is to use GCD's groups for that.
let backgroundQueue = DispatchQueue.global(attributes: .qosDefault)
let group = DispatchGroup()
var dataForTable:[String] = []
for number in 0..<n {
group.enter()
// Do your request with async callback, append data and leave GCD group.
backgroundQueue.async(group: group, execute: {
let newData = String()
dataForTable.append(newData)
group.leave()
})
}
group.notify(queue: DispatchQueue.main, execute: {
print("All requests data")
self.tableViewData = dataForTable
self.tableView.reloadData()
})
Upvotes: 1