Search code examples
iosswiftuicollectionviewcancellation

Any ideas to cancel a function in the middle? Swift iOS


I call a network task to fetch some JSON when user selects a cell in a UICollectionView. This is asynchronous so the UI remains active whilst the data is being retrieved. Allowing user to select another cell in the UICollectionView. I do not want to stop this but I do want a way to cancel the first function call and call the new method for the now selected cell.

Is there a way to in perhaps didDeselectItemAt indexPath: to cancel any currently executing tasks?

I was thinking to place a "please wait" modal view over the UI which would prevent a second cell selection until the function returned. Is this my best option or is there a better way?


Solution

  • You can use a NSOperationQueue to create and keep track of the asyncronous requests and cancel them when necessary.

    See the answers to this other question here: GCD cancel async block?