ProgressView in iOS

April 28, 2011 by · 2 Comments
Filed under: 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:


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
[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.


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.

Duplicates in Address Book: Some Progress on my next iPhone App

April 5, 2011 by · Leave a Comment
Filed under: DataQuality, iOS 

After trying out a few things during my last train rides to my consulting engagement, my next iPhone app is slowly taking shape.

Development progress

Here is a very rough, “in work” screenshot of what I have for now (using some test data):


Each cell in the TableView represents the contacts in the address book. The number in braces shows how “similar” another contact record is. (The number shown is for the “closest” record.) I want to make things a bit easier to spot by coloring the cells (e.g. red = 100% match, yellow between 90 and 100% match). I’ll also add some way to filter the displayed records (i.e. display only records above a certain threshold).

In the detail view, I want to display the “closest” records for one address and provide some way to look at the details of the involved contacts. (As this might require quite some back and forth between the different contact records, an iPad with additional screen estate may be a good idea here.) The detail view should also have some functionality to “remove” unwanted records (duplicates) or “merge” two records (collect all different phone numbers, email addresses etc. into one contact record and remove the other one).

Obviously, there is still a lot of work to do, but I’m making some progress. While I’m still looking for a good name, I already have an icon for the app: colored_background_clear_glass_512

Emerging Tiers

I’m also getting a clearer picture of which different modules I can offer:

  • Comparison – reading the address book and figuring out which records are close
  • Removing exact duplicates – Often, there are exact duplicates in the address book (for example after some technical problems with synching). These should be relatively simple to identify and delete.
  • Merging contact records – This is a lot more complicated as there are quite a few different scenarios. For example, you have to pick a “surviving” name (as there can be only one name), but there can be multiple addresses, phone numbers or email addresses.
  • Standardization – For some fields, different content can mean the same thing, e.g. “1231234567” is the same phone number as “123 123 4567” or “(123) 123-4567” or “+1-123-123 4567”. I’m not sure how much there can be done here, especially in addresses (Memory Lane = Memory Ln).
  • Once I get started, there’ll probably be more modules that make sense in the given context.

However, this looks like a good way to provide different tiers of the app:

  • entry level (low cost, maybe even free) – just offering the base comparison module
  • mid level – comparison plus dealing with exact duplicates
  • pro level – all modules as outlined above

This will also be a good scenario for “in app purchases” that I want to look into.