UILocalNotification Планирование оповещения - PullRequest
0 голосов
/ 16 февраля 2011

Я планирую Уведомление и выдаю ему предупреждение за 60 минут до того, как должно появиться предупреждающее сообщение ...

Как только я добавляю уведомление, вызывается метод в моем делегате приложения:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

Как я могу узнать, что он будет отображаться на заднем плане как предупреждение? Есть ли какой-либо другой метод делегата, который мне нужно переопределить или использовать, чтобы обеспечить получение запланированного оповещения с интервалом в 60 минут ...

- (void)scheduleNotificationWithItem:(NSDate *)item interval:(int)minutesBefore
{   
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    //NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *currentDateComponents = [calendar components:( NSWeekdayCalendarUnit | 
                                                                     NSYearCalendarUnit | NSMonthCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSWeekCalendarUnit | NSMinuteCalendarUnit) fromDate:item];

    NSLog(@"- current components year = %i , month = %i , week = % i, weekday = %i", [currentDateComponents year], [currentDateComponents month], [currentDateComponents week], [currentDateComponents weekday]);

    NSLog(@"[currentDateComponents minute]: %i",    [currentDateComponents minute]);
    NSLog(@"[currentDateComponents hour]: %i",      [currentDateComponents hour]);
    NSLog(@"[currentDateComponents day]: %i",       [currentDateComponents day]);
    NSLog(@"[currentDateComponents week]: %i",      [currentDateComponents week]);
    NSLog(@"[currentDateComponents month]: %i",     [currentDateComponents month]);
    NSLog(@"[currentDateComponents year]: %i",      [currentDateComponents year]);

    [dateComps setDay: [currentDateComponents day]];

    [dateComps setMonth:[currentDateComponents month]];

    [dateComps setYear:[currentDateComponents year]];

    [dateComps setHour:[currentDateComponents hour]];

    [dateComps setMinute:[currentDateComponents minute]];

    NSDate *itemDate = [calendar dateFromComponents:dateComps];

    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];

    if (localNotif == nil)
        return;

    localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];

    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    localNotif.alertBody = [NSString stringWithFormat:@"%@\n%@",
                            streetAddress,
                            stringOfWhenAuctionIsOn];

    localNotif.alertAction = NSLocalizedString(@"View Details", nil);

    localNotif.soundName = UILocalNotificationDefaultSoundName;

    localNotif.applicationIconBadgeNumber = 1;

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:streetAddress
                                                         forKey:idOfStreetAlert];

    localNotif.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

Ответы [ 2 ]

1 голос
/ 16 февраля 2011

Если уведомление появляется сразу же, возможно, что-то не так с вашим свойством fireDate. Похоже, вы пытаетесь проверить, верна ли отправленная дата, но вы также должны убедиться, что это то, что вы ожидаете.

Кроме того, вы могли бы, возможно, сделать

localNotif.fireDate = [item dateByAddingTimeInterval:-60*minutesBefore];

для достижения того же эффекта и не нужно возиться с NSDateComponents. Я не проверял это, но это может сработать.

Что касается того, что происходит, когда таймер срабатывает, а ваше приложение не работает. Если приложение не было закрыто, вызывается application:didReceiveLocalNotification:. Если, с другой стороны, ваше приложение было закрыто, вам нужно зарегистрировать application:didFinishLaunchingWithOptions:, как указано @Ishu. Обычно я просто передаю уведомление обычному методу, чтобы избежать дублирования кода.

0 голосов
/ 16 февраля 2011

Нет метода делегата для фона, вам нужно написать код в didFinishLaunchingWithOptions,

UILocalNotification *localNotif =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

    if (localNotif) {
        //your code
        NSLog(@"Recieved Notification %@",localNotif);
    }

это создает вашу логику, когда приложение получает уведомление от фона. Не беспокойтесь, приложение получает уведомление, если вы установили уведомление.

...