1

I would like to add a condition to my app that is based on if the user has used the app in the past week or not. What is the best way to do that? I read somewhere that I should used NSUseDefaults, but not sure how, I am just new to this.

thanks.

moshikafya
  • 3,190
  • 5
  • 22
  • 27
  • [This question](http://stackoverflow.com/questions/7553648/nsuserdefaults-storing-and-retrieving-data) might help. – Ken White May 09 '12 at 22:33
  • mmm...not so much...just shows a basic usage of NSUserDefaults. thanks though. – moshikafya May 09 '12 at 22:34
  • [And this one](http://stackoverflow.com/questions/9957055/how-to-store-an-retrieve-float-from-nsuserdefaults), which shows how to save a float. You can save and restore a date value the same way, or are you looking for someone to actually write the code for you? – Ken White May 09 '12 at 22:35

3 Answers3

5

Read:

self.lastRun = [NSDate distantPast];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"MyAppLastRun"]) {
    self.lastRun = [defaults objectForKey:@"MyAppLastRun"];
}    

Write:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.lastRun forKey:@"MyAppLastRun"];
[defaults synchronize];

Compare:

if ([[NSDate date] timeIntervalSinceDate:self.lastRun] > X) {
}

Note: assumes a property on self of NSDate *lastRun.

Joel
  • 15,654
  • 5
  • 37
  • 60
2

Yeh, just stick something in NSUserDefaults like so:

// When app comes to foreground:

NSDate *lastStartDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastStartDate"];

if (!lastStartDate) {
    // Never launched
} else if ([lastStartDate timeIntervalSinceNow] < -(60. * 60. * 24. * 7.)) {
    // Do whatever you want if they've not used in past week
}

[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastStartDate"];
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • So even though lastStartDate stores the "date", if you use it with timeIntervalSinceNow it will be converted to seconds? – moshikafya May 09 '12 at 22:39
  • Yes, it returns seconds. However, I find it more intuitive to switch the order so that the interval returns positive seconds not negative. [[NSDate date] timeIntervalSinceDate:lastStartDate]; – Joel May 09 '12 at 22:41
2

You can set a value in the applicationWillTerminate: like:

NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setObject:[NSDate date] forKey:@"lastUsed"];

Retrive the value:

NSDate *date=(NSDate*)[[NSUserDefaults standardUserDefaults]objectForKey:@lastUsed"];

Then compare the dates.

Mat
  • 7,613
  • 4
  • 40
  • 56