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.
+1
A:
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 scheduledTimerWithInterval:0.09f target:self selector:@selector(showElapsedTime:) userInfo:nil repeats:YES];
}
//...
@end
Jacob Relkin
2010-06-15 04:40:43
Thanks. how can I save this in iPhone's database? (save newDate on app exit)
Sam
2010-06-15 04:59:06
See paul's comment.
Jacob Relkin
2010-06-15 05:00:36
one last thing- how do I add two dates? newDate + totalDate
Sam
2010-06-15 05:15:47
Try `NSDate *addedDate = [newDate dateByAddingTimeInterval:[newDate timeIntervalSinceDate:startDate]];`
Jacob Relkin
2010-06-15 05:22:23
Do I need to use a loop to keep refreshing the time counter?
Sam
2010-06-15 05:32:25
Yes. I'll edit my answer.
Jacob Relkin
2010-06-15 05:38:51
thank you so much
Sam
2010-06-15 05:42:06
@Sam, sure. Can you upvote please? ;)
Jacob Relkin
2010-06-15 05:43:54
Sure. Trying to get NSUserDefaults to save data. It's not working. I put it viewDidUnload. Also, where should I load the data on app start.
Sam
2010-06-15 06:11:09
`applicationDidFinishLaunching`.
Jacob Relkin
2010-06-15 06:13:49
@Sam, catch me on AIM. My name lowercase without spaces.
Jacob Relkin
2010-06-15 06:16:00
im online now. ran in to another problem. NSDate *startDate = [NSDate date]; //initializer element not a constant
Sam
2010-06-15 07:49:19
@Sam, try it now.
Jacob Relkin
2010-06-15 14:43:05
+1
A:
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.
fbrereto
2010-06-15 04:41:44