如果日期更改,我需要执行一些操作。 意味着在应用程序启动时它会检查今天的日期,如果今天的日期与过去 24 小时的时间不同,那么它会执行一些操作。 是否可能,因为我们不需要运行后台线程。 我只想在委托(delegate)方法中添加某种条件。
喜欢: 如果在应用程序启动时首先保存今天的日期并保存该日期。 再次登录后,它将将该日期与当前日期进行比较,如果发现其 24 小时更改日期,则它将执行一些操作。我该怎么做?xc
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
最佳答案
在didFinishLaunchingWithOptions
方法中添加以下代码行
//for new date change
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timeChange) name:UIApplicationSignificantTimeChangeNotification object:nil];
YourApplicationDelegate.m
文件中的实现方法
-(void)timeChange
{
//Do necessary work here
}
编辑:混合@ZeMoon 的
答案会很完美,所以更改timeChange
方法
-(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
}
关于ios - 如果日期更改则执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628020/