iOS: простое локальное уведомление за 3 дня до - PullRequest
1 голос
/ 23 января 2012

Я написал приложение, которое позволяет пользователю вводить дату в окне выбора даты, а затем, когда они нажимают кнопку, он будет планировать локальное уведомление. Единственная проблема заключается в том, что уведомление срабатывает правильно, когда я нажимаю кнопку. Любая помощь высоко ценится! Вот мой код:

 - (IBAction)scheduleNotifButton:(id)sender {
        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [self.datePicker date];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-3];

NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];

        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        localNotif.fireDate = targetDate;
        localNotif.timeZone = [NSTimeZone defaultTimeZone];

        localNotif.alertBody = @"Event is in 3 days!";
        localNotif.alertAction = nil;

        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 0;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

    }

Ответы [ 2 ]

4 голосов
/ 23 января 2012

Вам нужно использовать [NSCalendar dateByAddingComponents:toDate:options:] вместо:

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [self.datePicker date];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-3];

NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];

[dateComponents release];

...
1 голос
/ 25 сентября 2012

Если вы ищете полный код о том, как запланировать уведомление чуть позже (например, 3 секунды), вот полный код:

ПРИМЕЧАНИЕ. Если вы находитесь внутри приложения, в верхней части экрана не будет отображаться окно сообщения, которое, возможно, придется обрабатывать через делегата UIApplication.

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

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [[NSDate alloc] init];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setSecond: 3 ];

NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];

localNotification.fireDate = targetDate;

localNotification.timeZone = [NSTimeZone defaultTimeZone];

localNotification.alertBody = @"Notified";
localNotification.alertAction = @"Show";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
...