簡體   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