Determining Elapsed Time
I recently wrote a short block of code to display an activity indicator while waiting for an image to be written to the iPhone camera roll. The problem I ran into is that the time to write the image file varies, depending on the image size. In some cases the activity indicator would be visible for a few seconds, other times the activity indicator flashed on/off screen so quickly, if you blinked, you’d miss it.
I needed a way to display the activity indicator a consistent amount of time for each file save, regardless of how long it took to write the file. Here’s the workaround I came up with – I began by saving the start time and creating an activity indicator:
// When did we start the image save ? // CFTimeInterval is a double (floating point number) CFTimeInterval startTime = CFAbsoluteTimeGetCurrent(); // Start the activity indicator UIActivityIndicatorView activityIndicator = [[UIActivityIndicatorView alloc] 100, 400, 30, 30]; activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; activityIndicator.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin); [activityIndicator sizeToFit]; [self.view addSubview:activityIndicator]; [activityIndicator startAnimating];
Next, I wrote the image to the camera roll and then checked for the amount of time elapsed:
// Save image code here... // How much time has elapsed ? CFTimeInterval difference = CFAbsoluteTimeGetCurrent() - startTime;
The last check I needed was to see if the amount of time that has elapsed was greater or less than the minimum time I wanted to display the activity indicator. If less than the desired amount of time, sleep for the amount of time needed to hit the minimum display time.
#define SECONDS_TO_DISPLAY_ACTIVITY_INDICATOR 3 ... // Determine if some predetermined amount of time has passed. if (difference < SECONDS_TO_DISPLAY_ACTIVITY_INDICATOR) [NSThread sleepForTimeInterval:SECONDS_TO_DISPLAY_SAVING_MSG - difference]; // Remove the activity indicator and message [activityIndicator stopAnimating]; [activityIndicator removeFromSuperview]; [activityIndicator release];
For my needs accuracy was not key. So even though CFTimeInterval is a double, I simply allow any rounding up or down to take place.
Related posts:
- Showing Network Activity When there Isn’t Any
- Xcode Debugging: Going Back in Time
- C++ on iPhone: Part 3, Run Time Type Identification


