如果日期改变则执行操作

时间:2014-10-29 10:31:04

标签: ios objective-c xcode datetime-format

如果日期改变,我需要执行一些操作。 在应用程序启动时的意思是检查今天的日期,如果今天的日期是从最后24小时的时间改变,那么它将执行一些操作。 是否有可能因为我们不需要运行后台线程。 我只想在委托方法中添加某种条件。

像: 如果在应用程序启动它首先保存今天日期并保存该日期。 再次登录后,它会将该日期与当前日期进行比较,如果将其更改为24小时更改日期,则会执行某些操作。我是怎么做到的?xc

  

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

2 个答案:

答案 0 :(得分:5)

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's回答这将完美地改变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
}

答案 1 :(得分:3)

您可以使用NSUserDefaults保存日期。

以下代码明确检查上次和当前应用启动之间的差异是否大于或等于24小时。然后它将当前日期保存在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;
}