2015-08-25 49 views
0

我正在尝试构建日历样式的应用程序,该应用程序提醒人们在事件发生前一天发生某些事件时。 我为此使用UILocalNotifications。 如果我想要显示通知,我必须重新启动我的应用程序。如何使UILocalNotification方法继续运行

无论应用程序是否仍在运行或关闭,我如何让此代码连续运行并按时显示通知?

我想知道如果我不得不把这个放到applicationDidEnterBackground方法使它工作吗?

目前我的代码看起来像这样

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){ 
     [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; 
    } 
    NSDate *today = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; 

    NSString* path = [[NSBundle mainBundle] pathForResource:@"example" 
                ofType:@"txt"]; 
    NSString* content = [NSString stringWithContentsOfFile:path 
                encoding:NSUTF8StringEncoding 
                error:NULL]; 
    NSArray* allLinedStrings = [content componentsSeparatedByCharactersInSet: 
           [NSCharacterSet newlineCharacterSet]]; 


    NSDate *tomorrow = [today dateByAddingTimeInterval:60*60*24*1]; 
    NSString *tomorrowString = [dateFormatter stringFromDate:tomorrow]; 

    for (int i = 0; i < allLinedStrings.count; i++) { 
     NSString* strsInOneLine = [allLinedStrings objectAtIndex:i]; 
     NSArray* singleStrs = [strsInOneLine componentsSeparatedByCharactersInSet: 
           [NSCharacterSet characterSetWithCharactersInString:@";"]]; 
     NSString *date = [singleStrs objectAtIndex:0]; 
     if ([date isEqualToString:tomorrowString]) { 
      for (int j = 1; j < singleStrs.count; j+=2) { 
       UILocalNotification *notification = [[UILocalNotification alloc]init]; 
       notification.fireDate = [NSDate dateWithTimeInterval:60*60*-24 sinceDate:tomorrow]; 
       notification.alertBody = [singleStrs objectAtIndex:j+1]; 
       notification.alertTitle = [singleStrs objectAtIndex:j]; 
       notification.timeZone = [NSTimeZone defaultTimeZone]; 
       [[UIApplication sharedApplication]scheduleLocalNotification:notification]; 
      } 
     } 
    } 

    // Override point for customization after application launch. 
    return YES; 
} 

回答

4

您的应用程序代码并不需要运行要显示你的本地通知。一旦您的应用程序调用scheduleLocalNotification:,通知将显示您的应用程序是否正在运行。

如果您的应用处于前台,您还需要实施application:didReceiveLocalNotification:。如果您希望自己的应用响应用户与通知进行交互而被打开,那么您需要实现application:handleActionWithIdentifier:forLocalNotification:completionHandler:

至于将通知安排在何处的代码应该放在应用中的任何位置知道要安排的事件。它只需要每个通知调用一次。它可以提前预定。