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

时间:2013-09-06 06:10:34

标签: iphone ios objective-c sqlite uilocalnotification

我有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];
 }

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果您想使用UILocalNotification,请参阅以下信息。

根据需要设置fireDate UILocalNotification,并在此日期生成通知。 并且您将以 2(两种)方式生成通知。,例如,

didFinishLaunchingWithOptions

中的

1)

=>如果您的应用程序没有运行,它会很有用;

- (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
}

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

答案 2 :(得分:0)

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
}