techno
techno

Reputation: 6518

Grand Central Dispatch-Check for Task Completion

I want to do a lengthy background operation;after completion I need to refresh a TableView

let globalQueue = DispatchQueue.global()
                globalQueue.async {
                   //My lengthy code 
                }

I need to do this after the Async Task Completes

 treeview.reloadData()

How can I hook to GCD Task completion Event? I have C# Background, I'am new to SWIFT.. Please advice.

Upvotes: 0

Views: 239

Answers (2)

Infinity James
Infinity James

Reputation: 4735

I would suggest using a DispatchGroup. With a group you can create dependencies and be notified when everything has completed.

// create a group to synchronize our tasks
let group = DispatchGroup()

// The 'enter' method increments the group's task count…
group.enter()
let globalQueue = DispatchQueue.global()
globalQueue.async {
    // my lengthy code 
     group.leave()
}

// closure will be called when the group's task count reaches 0
group.notify(queue: .main) { [weak self] in
    self?.tableView.reloadData()
}

Upvotes: 1

Papershine
Papershine

Reputation: 5223

You just need to place it in a main queue after your code:

let globalQueue = DispatchQueue.global()
globalQueue.async {
    // Your code here
    DispatchQueue.main.async {
        self.treeview.reloadData()
    }
}

Upvotes: 3

Related Questions