ProgressView in iOS

When you are doing some longer running operation in a program, you want to give some feedback to the user. This blog post looks at some ways on how to do this in iOS. I’m using my ongoing work on my next iPhone app “SmarterContacts” [include link] which will find and eliminate duplicates in your iPhone contacts.

Providing meaningful progress feedback to the user

One of the strengths of the iPhone interface is its constant and almost immediate feedback to the user. For example, if you scroll through a long TableView, it feels as if you are grabbing the contents and “throw” it up. You can tell that a lot of work has been put into this user experience, and it’ obvious that you should avoid breaking this feedback loop when writing your own apps.

But sometimes there are operations in an app that are going to take some time. As a rough guideline, anything that takes longer than a few tenths of a second, there should be some feeback to the user that the program is doing something and hasn’t crashed. iOS offers some way of providing this feedback:

  • ActivityIndicator image
    In iOS, this is an animated “spinning wheel” that shows that something is still going on. Other OSs use the same idea, but a different metaphor (OSX has the beachball on earlier Mac versions it was watch, Windows used to have an Hourglass and now has a rotating orb.) The ActivityIndicator is the simplest way to provide feedback – you just add one to the current view, start it spinning, do your operation and then remove the it.
    One important drawback is that the ActivityIndicator doesn’t give any feedback to the user about actual progress, i.e. how far along is the operation and how much longer is it going to take. This is not a problem for operations that are reliable and take just a few seconds. But for anything longer, the user might give up on the program.
  • ProgressBar image
    This is a bar that starts empty and gets filled when the operation is progressing. When it is completely full, the operation is completed. (A little side note: In some dialogs – notably in older Windows file copying dialogs and a lot of installation programs – the bar empties after it has been filled and then starts to fill again, over and over. This degrades the ProgressBar to just an ActivityIndicator with all its disadvantages, but using a lot more space and disappointing the user who will think the operation is done when the bar is filled for the first time. Definitely not recommended.)
    The ProgressBar provides much more feedback to the user: It shows that the program is still making progress as the bar nudges on and on, and it allows the user to make a rough estimate of how much work is left. However, it requires a bit more work by the programmer to update the ProgressBar. It also requires the programmer to figure out what “80%" done” means – this is sometimes tricky when there are a lot of different steps involved.

In my app one long running operation is comparing the different contacts and figuring out how “similar” they are to one another. As this requires comparing each record to all other contacts, the program has a characteristic of O(n^2) which quickly gets noticeable when working on more than 100 records. Therefore, I want to provide feedback to the user while this operation runs. As this takes more than a few seconds (even in the simulator, which is a lot faster than my iPhone 3GS), I wanted to use a ProgressBar. I also wanted to provide some additional feedback (such as “at record x of y” and “z seconds remaining”), so I built a nice looking ProgressView.

A first stab at a ProgressView

The ProgressView looks like this:

image

It consists of a few labels (for the title, the number of records and the remaining time) and a ProgressBar. The trickiest thing here is the positioning of all the items on the screen. (I’m sure the code I have is a bit clumsy and can be improved. Suggestions are welcome, please add a comment.)

//add top Label
topLabel = [[UILabel alloc] initWithFrame:
                     CGRectMake(0, gutter, width-4*gutter, 20.)];
[topLabel setCenter: CGPointMake(center.x, center.y - 30.)];
[topLabel setText: @"[Being busy]"];
[topLabel setTextAlignment:UITextAlignmentCenter];
[self addSubview: topLabel];

//add Progress Bar
progbar = [[UIProgressView alloc] initWithFrame:
                           CGRectMake(0, 0, width-4*gutter, 20.)];
[progbar setCenter: center];
[progbar setProgress: 0.];
[progbar setProgressViewStyle:UIProgressViewStyleBar];
[self  addSubview: progbar];    

//add progress Label
progLabel = [[UILabel alloc] initWithFrame:
                      CGRectMake(0, 0, width-4*gutter , 20.)];
[progLabel setCenter:CGPointMake(center.x, center.y + 10.)];
[progLabel setTextAlignment:UITextAlignmentCenter];
[progLabel setText: [NSString stringWithFormat: @"At record %i of %i", currentValue, maxValue]];
[self addSubview: progLabel];  

// add remaining time label
remainingLabel = [[UILabel alloc] initWithFrame:
                           CGRectMake(0, 0, width-4*gutter , 20.)];
[remainingLabel setCenter:CGPointMake(center.x, center.y + 30.)];
[remainingLabel setTextAlignment:UITextAlignmentCenter];
[remainingLabel setText: @"Calculating remaining time ..."];
[self addSubview: remainingLabel];  

It is displayed as a little “dialog box” on the screen and “dims” the view that it is called from by using a semi-transparent background:

[self setBackgroundColor: [UIColor colorWithRed:204./255 green:213./255 blue:216./255 alpha:0.5]];

The ProgressView can be updated by calling the “setCurrentValue” method which then updates all the labels and the progress bar:

-(void) setCurrentValue:(NSInteger)newCurrentValue {
    currentValue = newCurrentValue;
    if (currentValue % stepValue == 0) { //% is modulus
        [progLabel setText: [NSString stringWithFormat: @"At record %i of %i", currentValue, maxValue]];
        [progbar setProgress: (float) (currentValue) / maxValue];
        
        if (currentValue > 0 && abs([startTime timeIntervalSinceNow]) > 0) {
            int remaining = trunc (abs([startTime timeIntervalSinceNow]) 
                                   * (maxValue - currentValue) / currentValue);
            [remainingLabel setText: [NSString stringWithFormat: @"About %i seconds remaining", remaining]];
        } else {
            [remainingLabel setText: @"Calculating remaining time ..."];
        }
    }
}

All that’s left to do, is to open the view at the start of the long-running operation using addSubview: and then update the ProgressView by calling setCurrentValue:. When the operation is done, we just remove the ProgressView using removeFromSuperview.

This almost works .. the ProgressView is displayed at the start and removed at the end of the operation, but then it is not updated during the operation – which means no feedback to the user and it looks like the program crashed.

Making it work using threading

The reason for this behavior is that the screen is not updated while the operation executes – I’m not exactly sure when the update would occur (unless when the whole operation is over). This is because the simple program is unthreaded, i.e. there is no thread that is available to update the screen. In VisualBasic there is the expression “Do Events” which basically turns control over to the OS to process screen updates, user inputs etc.  There does not seem to be an equivalent expression in iOS, instead we have to delve a bit into threading to separate between the screen updates and the calculation.

Setting up the threading environment

In earlier versions of iOS it was quite a lot of work to set up the threading environment. Since version [???] this has been made a lot easier by providing NSOperationQueue and NSInvocationOperation. Now all that is left to is:

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = 
  [[NSInvocationOperation alloc] initWithTarget:self
                                       selector:@selector()
                                         object:nil];
[queue addOperation:operation];
[operation release];

The NSOperationQueue basically set ups the threading environment, so that as soon as an operation is added to the queue, the execution is started in a secondary thread.

Updating the ProgressView

This secondary thread is then executing the long running operation, while the primary thread can still update the screen. Within our operation we can trigger the screen update in the main thread:

[self performSelectorOnMainThread:@selector(updateProgress) 
                       withObject: nil waitUntilDone:YES];

I’ve had some problems passing an object using the “withObject:” selector, probably because I was using memory that was only available to the secondary thread. (Probably because it was allocated by the secondary thread.) Instead, I was able to use a property of the view that created the secondary thread.

Tearing down

All that was left to do was to remove the view when the operation is done. This is achieved by calling

[self performSelectorOnMainThread:@selector(calculationDone) withObject:nil waitUntilDone:YES];

Again, this calls the main thread to notify that the calculation is done and that the ProgressView can be removed.

Summary

We’ve managed to build a good looking, informative ProgressView. In addition to implementing the code to display, update and remove the view, we also had to make sure that the ProgressView is updated on the screen by creating and using a secondary thread. The additional code required for the threading was quite small, and it was able to use the original, unchanged code for the ProgressView.


Posted

in

by

Tags:

Comments

2 responses to “ProgressView in iOS”

  1. eu vid Avatar
    eu vid

    Do you have attached a source code for this tutorial?

  2. Thorsten Avatar
    Thorsten

    Hi,
    at this point I do not have a full project that can be downloaded. I’m hoping that the code I posted is sufficient to add the ProgressView to your own project.
    All my best
    Thorsten

Leave a Reply

Your email address will not be published. Required fields are marked *