Jonas Zaugg Jonas Zaugg - 3 months ago 8
Swift Question

Handling user interaction while waiting for segue after download using Alamofire

My project displays elements in a Table View. When the user clicks a cell, the cell expands to show more info (like the App Store updates tab) and if the user taps that expanded cell, the element referred in the cell is opened in a new page (again, like the App Store). That element however has to be downloaded using an Alamofire request before it can be shown. To speed things up, I'm starting the download the element when the cell expands so when the user decides to open the element, it might already have finished downloading.

However herein lies my issue : some elements download quickly so it's very likely downloaded when the user opens the element (second tap). Some elements however are much larger and take longer to download (up to 6 seconds). How should I handle user input if the element hasn't finished downloading yet and, moreover, how should I implement it?

The easiest way was to ignore user input completely, checking if the element has downloaded with each tap to launch the segue. However it feels wrong to ignore the user and for them to have to tap more than once with the same intent. Similarly, I've used

dispatch_group_wait()
on the main thread but it's even worse because it blocks all input.

What I would like to achieve is the following :


  1. First tap : start download request and retain it in a variable (that's already done). I don't want to launch the segue in the request's
    completionHandler
    because we don't know yet if the

  2. Second tap :

    a. If the element has downloaded, launch the segue to open it.

    b. If the element has not yet finished downloading, postpone the launch of the segue to the end of the download.



I'm aware this question is very large so to narrow it down : is it possible to implement the aforementioned logic? How?

Answer

You can use the shouldPerformSegueWithIdentifier: function to cancel a segue.

Implement this function and use it to cancel the segue if the item hasn't downloaded yet and also set a flag that the download completion handler can check.

When the download is complete, if the flag is set the completion handler can perform the segue.

You should probably also show some sort of activity indicator so that the user knows that the data is loading

Comments