ios - 如果日期更改则执行操作

标签 ios objective-c xcode datetime-format

如果日期更改,我需要执行一些操作。 意味着在应用程序启动时它会检查今天的日期,如果今天的日期与过去 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/

相关文章:

ios - 如何处理模型类中的数组?

iphone - Facebook IOS SDK 可选权限

objective-c - ios 6 应用程序正在旋转,即使使用 shouldAutorotate :NO

iphone - NSUserDefaults setObject 和 IntegerForKey,在同一个键上使用,如果不是,我该如何解决?

xcode - 在 OS X Tableview 中显示的 Swift 核心数据

iOS/Xcode : is there a difference between running the App on an iPhone while connected to Xcode compared to opening the installed App afterwards?

ios - 我如何在第 2 代 SKSpriteNode 之间等待?

ios - 构建应用程序时找不到 Cocoapods header

ios - UISwitch 双击

iphone - Xcode: "Build and run"无需重启 iPhone 模拟器