繁体   English   中英

如何在变更日期时采取行动?

[英]How to fire action on date change?

我有Sqlite数据库。

我想在日期更改时在数据库中插入行。

我只知道我应该使用UILocalNotification ,但是我不知道。

另一种方法是在后台运行NSTimer,但我不想这样做。

从我尝试的教程中:

UIApplication* app = [UIApplication sharedApplication];
NSDate *date = [NSDate date]; 
// create the notification and then set it's parameters
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
if (notification)
{

    notification.fireDate = date;
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.repeatInterval = 0;
    notification.alertBody = @"DONE:";

    // this will schedule the notification to fire at the fire date
    [app scheduleLocalNotification:notification];

    // this will fire the notification right away, it will still also fire at the date we set
    [app presentLocalNotificationNow:notification];
 }

但在我的应用中,它应该插入数据库中,或者应用是在后台还是在前台。 日期更改时应插入

您可以存储[NSDate日期]; 对某个变量并根据最后日期放置条件,并使用[NSDate date]使用今天的日期在该条件内更改该变量; 并根据需要进行修改

如果要使用UILocalNotification请参阅以下信息。

根据需要设置fireDateUILocalNotification ,您的通知将在该日期生成。 您将以两种(两种)方式获得生成的通知 像这样

1)didFinishLaunchingWithOptions

=>如果您的应用程序未运行,这将很有帮助;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   .
   .
   .
   UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
   if (localNotif) 
   {
      /// do your stuff
   }
   .
   .
}

2)使用UILocalNotification委托方法

=>如果您的应用程序正在运行,这将很有帮助;

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
    /// do your stuff
}

您可以在此处写入插入数据;

将此代码添加到didFinishLaunchingWithOptions方法中

// date change
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dateChange) name:UIApplicationSignificantTimeChangeNotification object:nil];

YourDelegate.m文件中的实现方法

-(void)dateChange
{
  if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LastAppOpenTime"] != nil)
  {
    NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastAppOpenTime"];
    NSDate *currentDate = [NSDate date];

    NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:lastDate];
    double secondsInAnHour = 3600;
    NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

    if (hoursBetweenDates >= 24)
    {
        //update database here.
    }
  }

  [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastAppOpenTime"];//Store current date
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM