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.
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.
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.
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"];
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.