Как узнать, какое локальное уведомление было получено? Цель - С

У меня есть этот фрагмент кода, который вызывает другой оператор NSLog в зависимости от того, какое локальное уведомление было получено:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    if (notification == automaticBackupNotification)
    {
        NSLog(@"Backup notification received.");
    }
    else
    {
        NSLog(@"Did receive notification: %@, set for date:%@ .", notification.alertBody, notification.fireDate);
    }
}

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

- (IBAction)automaticValueChanged {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (automaticSwitch.isOn){
        [defaults setValue:@"1" forKey:@"automatic"];
        //schedule notification
        //Set up the local notification
        appDelegate.automaticBackupNotification = [[UILocalNotification alloc] init];
        if(appDelegate.automaticBackupNotification){
            //Repeat the notification according to frequency
            if ([backupFrequencyLabel.text isEqualToString:@"Daily"]) {
                appDelegate.automaticBackupNotification.repeatInterval = NSDayCalendarUnit;
            }
            if ([backupFrequencyLabel.text isEqualToString:@"Weekly"]) {
                appDelegate.automaticBackupNotification.repeatInterval = NSWeekCalendarUnit;
            }
            else {
                appDelegate.automaticBackupNotification.repeatInterval = NSMonthCalendarUnit;
            }

            //Set fire date to alert time
            NSCalendar *calendar = appDelegate.automaticBackupNotification.repeatCalendar;
            if (!calendar) {
                calendar = [NSCalendar currentCalendar];
            }

            NSDateComponents *components = [[NSDateComponents alloc] init];
            components.day = 1;
            //NSDate *nextFireDate = [calendar dateByAddingComponents:components toDate:[NSDate date] options:0];
            //appDelegate.automaticBackupNotification.fireDate = nextFireDate;
            appDelegate.automaticBackupNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20.0];

            //Set time zone to default
            appDelegate.automaticBackupNotification.timeZone = [NSTimeZone defaultTimeZone];

            // schedule notification
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:appDelegate.automaticBackupNotification];

            NSLog(@"Backup Fire Date: %@", appDelegate.automaticBackupNotification.fireDate);
        }
    }
    else {
        [defaults setValue:@"0" forKey:@"automatic"];
        if(appDelegate.automaticBackupNotification){
            [[UIApplication sharedApplication] cancelLocalNotification:appDelegate.automaticBackupNotification];
        }
    }

    [defaults synchronize];
}

Однако, когда делегат приложения получает уведомление, он запускает «else» часть условного выражения. Можно ли как-то отличить разные уведомления? Или я что-то не так делаю?

Ваше здоровье,

Тысин


person Jack Nutkins    schedule 03.08.2012    source источник


Ответы (3)


Объект NSNotification имеет свойство, вызываемое userInfo. Это NSDictionary, вы можете установить некоторые значения, в которых вы создаете уведомление, и проверять их там, где вы его получаете.

person Mert    schedule 03.08.2012

Просто попробуйте установить свойство userInfo вашего UILocalNotification, вот так:

NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"YOUROBJECT" forKey:@"TESTKEY"];
YOURNOTIFICATION.userInfo = userDict;

и когда UILocalNotification срабатывает, эти методы будут вызываться,

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
     NSDictionary *dict = [notification userInfo];
     id obj = [dict objectForKey:@"TESTKEY"];
}

Основываясь на userInfo, который вы установили во время настройки UILocalNotification, вы можете узнать, какой notification был вызван.

person Mehul Mistri    schedule 03.08.2012

Я лично использую имя уведомления, чтобы узнать, какие уведомления были отправлены или получены

//add local observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mathodCalled:) name:[NSSTring StringWithFormat :@"plop"] object:nil];

...

//push an event manually 
[[NSNotificationCenter defaultCenter] postNotificationName:eventName object:[NSSTring StringWithFormat :@"plop"]];

...

- (void)methodCalled :(NSNotification*)aNotification{
    if([aNotification.name isEqualToString:@"plop"]){
        // do something
    }

}
person Omaty    schedule 03.08.2012