Sam
Sam

Reputation: 75

iphone app time counter

I would like to create a time counter in my app that shows the user how many minutes the app has been running the current session and total. How do I create such time counter and how do I save the value to the phone? I'm new to app developement.

Upvotes: 1

Views: 780

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163258

You can use the NSDate and NSDateFormatter classes for this.

Here's an example:

Declare an NSDate instance in your .m file:

@implementation MyClass 

NSDate *startDate;
BOOL stopTimer = NO;
//...    

-(void) showElapsedTime: (NSTimer *) timer {
    if(!startDate) {
        startDate = [NSDate date]; 
    }
    NSTimeInterval timeSinceStart = [[NSDate date] timeIntervalSinceDate:startDate];
    NSDate *newDate = [[NSDate alloc] initWithTimeInterval:timeSinceStart sinceDate:startDate];
    NSString *dateString = [NSDateFormatter localizedStringFromDate:newDate dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle];


    //do something with dateString....

    if(stopTimer) {//base case
       [timer invalidate];
    }
    [newDate release];
}

- (void) startPolling {
    [NSTimer scheduledTimerWithTimeInterval:0.09f target:self selector:@selector(showElapsedTime:) userInfo:nil repeats:YES];
}

//...

@end

Upvotes: 3

fbrereto
fbrereto

Reputation: 35925

On the iPhone you can use the API CFAbsoluteTimeGetCurrent() to get a numeric value for the current date and time. You can call this twice and subtract the two numbers from each other to get an elapsed time between those calls. You can then save that elapsed time between executions of your program to save the total time the user has had your program running.

Upvotes: 2

Related Questions