如何让UILocalNotification方法继续运行

时间:2015-08-25 22:18:43

标签: ios objective-c uilocalnotification

我正在尝试构建一个日历风格的应用程序,以便在某些事件发生前一天发生时提醒人们。 我正在使用UILocalNotifications。 如果我想要显示通知,我必须重新启动我的应用程序。

如果应用程序仍在运行或已关闭,如何及时显示通知,我怎样才能继续运行此代码?

我想知道是否必须将其放入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;
}

1 个答案:

答案 0 :(得分:4)

您的应用代码无需运行即可显示本地通知。应用调用scheduleLocalNotification:后,通知会显示您的应用是否正在运行。

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

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