Reputation: 5545
i need to perform some action if date change. Means at the time of app launch it check the today date, and if today date is change from last 24 hour time,then it will perform some action. Is it possible as we don't need to run background thread. I just want to add some sort of condition in delegate method.
like : if on app launch it first save today date and save that date. After again login it will compare that date with current date and if fount its 24 hour change date then it will perform some operation. how i do that?xc
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Upvotes: 0
Views: 283
Reputation: 38249
Add below line of code in didFinishLaunchingWithOptions
method
//for new date change
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timeChange) name:UIApplicationSignificantTimeChangeNotification object:nil];
Implement method in YourApplicationDelegate.m
file
-(void)timeChange
{
//Do necessary work here
}
EDIT : Mixing @ZeMoon's
answer this would work perfect so changes in timeChange
method
-(void)timeChange
{
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LastLoginTime"] != nil)
{
NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastLoginTime"];
NSDate *currentDate = [NSDate date];
NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:lastDate];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
if (hoursBetweenDates >= 24)
{
//Perform operation here.
}
}
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastLoginTime"];//Store current date
}
Upvotes: 5
Reputation: 20274
You can use NSUserDefaults to save the date.
The following code explicitly checks whether the difference between the last and current app launch is more than or equal to 24 hours. It then saves the current date in the userDefaults.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LastLoginTime"] != nil)
{
NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastLoginTime"];
NSDate *currentDate = [NSDate date];
NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:lastDate];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
if (hoursBetweenDates >= 24)
{
//Perform operation here.
}
}
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastLoginTime"];//Store current date
return YES;
}
Upvotes: 3