How to implement LocalNotification using Objective-C?

20,946

Solution 1

1) When the app is closed, schedule a local notification that will fire in 24 hours

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
    notification.alertBody = @"24 hours passed since last visit :(";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

2) if the app is opened (before the local notification fires), cancel the local notification

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

//For local Notification

first thing we need to do is register the notifications.

 // New for iOS 8 - Register the notifications
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

Now let’s create the notification itself

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    if (notification)
    {
            notification.fireDate = _datePicker.date;

            NSDate *fireTime = [[NSDate date] addTimeInterval:10]; // adds 10 secs
            notification.fireDate = fireTime;
            notification.alertBody = @"Alert!";

            notification.timeZone = [NSTimeZone defaultTimeZone];
            notification.applicationIconBadgeNumber = 1;
            notification.soundName = UILocalNotificationDefaultSoundName;
            switch (_frequencySegmentedControl.selectedSegmentIndex) {
                case 0:
                    notification.repeatInterval = NSCalendarUnitDay;
                    break;
                case 1:
                    notification.repeatInterval = NSCalendarUnitWeekOfYear;
                    break;
                case 2:


           notification.repeatInterval = NSCalendarUnitYear;
                break;
            default:
                notification.repeatInterval = 0;
                break;
        }
        notification.alertBody = _customMessage.text;

Once we have the notification created we need to schedule it with the app.

// this will schedule the notification to fire at the fire date
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
// this will fire the notification right away, it will still also fire at the date we set
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];

If we leave things the way they are now a notification will only appear on screen if the app is in the background. In order to display something when the app is in the foreground and a notification fires we need to implement a method in the app delegate.

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notification Received" message:notification.alertBody delegate:nil     cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}

We added a icon badge to our app, and this icon badge will only display when the app is in the background. Generally you want to dismiss the icon once a user has opened the app and seen the notification. We’ll need to handle this in the app delegate as well.

These two methods will take care of it.

- (void)applicationWillEnterForeground:(UIApplication *)application 
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"%s", __PRETTY_FUNCTION__);
    application.applicationIconBadgeNumber = 0;
}

- (void)applicationDidBecomeActive:(UIApplication *)application 
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"%s", __PRETTY_FUNCTION__);
    application.applicationIconBadgeNumber = 0;
}

Solution 2

iOS 10 by Apple document:

UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
            arguments:nil];
content.sound = [UNNotificationSound defaultSound];
 
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
            triggerWithTimeInterval:5 repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
            content:content trigger:trigger];
 
// Schedule the notification.
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:nil];
Share:
20,946
AnswerMe
Author by

AnswerMe

Updated on May 06, 2022

Comments

  • AnswerMe
    AnswerMe about 2 years

    I am trying to implement local notification in my application. I don't know how to do properly, below code I am using for new data arrival process, here after how to implement Notification process and I need notifications during both foreground and background modes.

    Below I had successfully background fetching process for new data arrival checking method

    //  Value matching and trying to get new data 
    [live_array removeObjectsInArray:stored_array];
           
    // if you require result as a string
    NSString *result = [stored_array componentsJoinedByString:@","];
    NSLog(@"New Data: %@", result);   // objects as string:
    

    Above code finally giving some string value...Once the value came I want to show the notification. Everything I am doing is in the App Delegate.

  • Mehul
    Mehul almost 9 years
    Just change the 60*60*24 to 30 (this is the number of seconds from now)
  • AnswerMe
    AnswerMe almost 9 years
    Hi another one plm I cant see notification on notification device panel top side and sounds also not comming. plz hel me @Mehul
  • Mehul
    Mehul almost 9 years
    please, trying to set in Device not in Simulator.
  • AnswerMe
    AnswerMe almost 9 years
    Ok. what about top side dashboard I cant see anythign on notification panel
  • AnswerMe
    AnswerMe almost 9 years
    On notification widgets nothing messages. I can see badges and alert. I am asking If I scroll down from iphone simulator from top there nothing widget messages. @Mehul
  • Mehul
    Mehul almost 9 years
    UILocalNotification *localNotif = [[UILocalNotification alloc] init]; if (localNotif == nil) return; NSDate *fireTime = [[NSDate date] addTimeInterval:10]; // adds 10 secs localNotif.fireDate = fireTime; localNotif.alertBody = @"Alert!"; [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
  • Mehul
    Mehul almost 9 years
    @AnswerMe, i have edited my code, check i had edited time interval of 10 Sec.
  • AnswerMe
    AnswerMe almost 9 years
    no, I am telling about widget. Notification widget not showing anything. Its not time problem i think. In my code I have added 30 seconds. Sound and widget not working. I am tesing by simulator only!
  • Mehul
    Mehul almost 9 years
    @AnswerMe, i think you have to test in Device.. i dont have any idea what happen in simualtor my friend.
  • AnswerMe
    AnswerMe almost 9 years
    Ok thank you so much friend! Keep on help to all. great work!Mehul.