2014-10-29 64 views
0

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

like: 如果在应用上启动它,则先保存今天的日期并保存该日期。 再次登录后,它会将该日期与当前日期进行比较,如果从它的24小时更改日期开始,那么它将执行一些操作。我该怎么办?XC

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

回答

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; 
} 
+0

谢谢Zemoon,快速回答你的代码似乎适合我。 .... – iphonemaclover 2014-10-29 10:47:16

+0

这将工作,但当应用程序是开放的和新的日期变化,那么这将无法正常工作。 – 2014-10-29 10:48:29

+1

OP特别想要在应用程序启动时检查24小时的时间间隔。该代码完全符合该要求。 – ZeMoon 2014-10-29 10:50:11

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 
} 
+0

你好王子是这个通知工作,即使应用程序终止并重新启动? – iphonemaclover 2014-10-29 10:43:21

+0

是的,只要有新的或旧的日期改变,这就像一个魅力,因为我不得不打电话给新的日期的数据。 – 2014-10-29 10:45:23

+0

感谢价格..... upvote来填补我的日期变化查询,但我接受Zemoon答案作为接受的答案,因为使用它,我可以与几个小时... – iphonemaclover 2014-10-29 10:50:10