Search code examples
iosswiftconcurrencyuicollectionviewgrand-central-dispatch

Interface should be changed before time-consuming task starts in Swift


I'm trying to implement the following behaviour of collectionView cell: by tapping on the cell the appearance of the cell should be changed first! And AFTER that, a time-consuming process should start:

@objc private func addItemsToBasket(_ button: UIButton) {
         button.setTitleColor(.clear, for: .normal)
         Basket.addItems(keys: planner.currentDayKeys())
}

but unfortunately, the cell changes appearance only after the time-consuming block is finished. If I comment "Basket.addItems(keys: planner.currentDayKeys())" the cell changes its appearance prompt.

I have already tried different options in GCD, nothing helped. But actually, if I don't define a Queue the code should run line by line. Right?

It should be a very common case. Thank you in advance for any ideas.


Solution

  • Like mentioned in the comments, you should not perform time consuming tasks on the main queue. GCD will definitely help you in this case. Have you tried something like this:

    @objc private func addItemsToBasket(_ button: UIButton) {
        button.setTitleColor(.clear, for: .normal)
        DispatchQueue.global.async {
            Basket.addItems(keys: self.planner.currentDayKeys())
        }
    }
    

    But you need to make sure that if you do some UI changes in your Basket.addItems, you need to dispatch them back to main by wrapping them inside a DispatchQueue.main.async closure.