Add a running countup display timer to an iOS app, like the Clock stopwatch?

Alex Stone picture Alex Stone · Aug 22, 2012 · Viewed 20.4k times · Source

I'm working with an app that processes device motion events and updates interface in 5 second increments. I would like to add an indicator to the app that would display the total time the app has been running. It seems that a stopwatch-like counter, like the native iOS Clock app is a reasonable way to count time that the app has been running and display it to the user.

What I'm not sure of is the technical implementation of such a stopwatch. Here's what I'm thinking:

  • if I know how long between interface updates, I can add up seconds between events and keep a count of seconds as a local variable. Alternatively, a 0.5 second interval scheduled timer can provide the count.

  • If I know the start date of the app, I can convert the local variable to date for each interface update using [[NSDate dateWithTimeInterval:(NSTimeInterval) sinceDate:(NSDate *)]

  • I can use a NSDateFormatter with a short time style to convert the updated date to a string using stringFromDate method

  • The resulting string can be assigned to a label in the interface.

  • The result is that the stopwatch is updated for each "tick" of the app.

It appears to me that this implementation is a bit too heavy and is not quite as fluid as the stopwatch app. Is there a better, more interactive way to count up time that the app has been running? Maybe there's something already provided by iOS for this purpose?

Answer

terry lewis picture terry lewis · Aug 22, 2012

If you look in the iAd sample code from Apple in the basic banner project they have a simple timer:

NSTimer *_timer; 
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];

and the the method they have

- (void)timerTick:(NSTimer *)timer
{
    // Timers are not guaranteed to tick at the nominal rate specified, so this isn't technically accurate.
    // However, this is just an example to demonstrate how to stop some ongoing activity, so we can live with that inaccuracy.
    _ticks += 0.1;
    double seconds = fmod(_ticks, 60.0);
    double minutes = fmod(trunc(_ticks / 60.0), 60.0);
    double hours = trunc(_ticks / 3600.0);
    self.timerLabel.text = [NSString stringWithFormat:@"%02.0f:%02.0f:%04.1f", hours, minutes, seconds];
}

It just runs from start up, pretty basic.