Search code examples
objective-ciosnstimernstimeinterval

Best way to calculate and save user use time in application


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!


Solution

  • 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.