0

What is the best way to calculate the user's use time in my application. Is it ok to save it in NSUserDefaults? In which format I should save it?

I want to know if the user lets say played the app 3-4 times, each time he has been playing for 2 hours, so I want the time each time to be added to previous time, so now I will have there 6 hours.

Thanks!

ytpm
  • 4,962
  • 6
  • 56
  • 113

1 Answers1

2

I'd indeed suggest to use NSUserDefaults.

Store the current date in an ivar of your app delegate in didFinishLaunching:

in your AppDelegate.h:

NSDate *startTime;

and in your .m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  startTime=[NSDate date]; //stores the current time in startTime
}

Now each time the user pauses/closes the app, calculate the difference between startTime and the current time and add it to a value in your NSUserDefaults:

- (void)applicationDidEnterBackground:(UIApplication *)application {
  double diff=[startTime timeIntervalSinceNow]*(-1); //timeIntervalSinceNow is negative because startTime is earlier than now
  NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
  [defaults setDouble:[defaults doubleForKey:@"Time"]+diff forKey:@"openedTime"]
}

And store the current date in didBecomeActive again:

- (void)applicationDidBecomeActive:(UIApplication *)application {
startTime=[NSDate date];
}

You can then get the use time until now using

double usedTime=([startTime timeIntervalSinceNow]*(-1))+[[defaults doubleForKey:@"Time"] doubleForKey:@"Time"];

If you just want to get the opened time since the last time the user started the app, reset the openedTime in didFinishLaunching

[defaults setDouble:0.0f forKey:@"openedTime"]

Hope this helps.

FD_
  • 12,947
  • 4
  • 35
  • 62
  • It does! Thank you, but why you did the *(-1) in the application did enter background? – ytpm Nov 03 '12 at 06:20
  • Also, it's not that good, because I want to know inside the application the current use time, but on the first play it's not possible at all, and it wont save the current time until you quit the app. Maybe you've got another way? – ytpm Nov 03 '12 at 06:40
  • I've added additional information on how to get the use time anywhere. In fact,the above code saves the use time every time the user changes to another app, which is the most efficient way in my opinion. – FD_ Nov 03 '12 at 17:15