LocalNotification In iPhone OS4

In this application we will see how to LocalNotification worked. Basically, apple has added new services called Local Notification, which lets apps lunch notifications without the need for an external server.

Step 1: Create a Window base application using template. Give the application name “Multitusking_LocalNotify”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: In the Multitusking_LocalNotifyAppDelegate.h file, we have added one instance variable bgTask. So make the following changes in the file:

 

#import <uikit/UIKit.h>

@interface Multitusking_LocalNotifyAppDelegate : NSObject {
UIWindow *window;
UIBackgroundTaskIdentifier bgTask;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

 

 

Step 4: Open the Multitusking_LocalNotifyAppDelegate.m file , and make the following changes in  the file.

 

@interface ItemList : NSObject {
NSInteger year;
NSInteger month;
NSInteger day;
NSInteger hour;
NSInteger minute;
NSInteger second;
NSString *eventName;
}

@property (nonatomic, readwrite) NSInteger year;
@property (nonatomic, readwrite) NSInteger month;
@property (nonatomic, readwrite) NSInteger day;
@property (nonatomic, readwrite) NSInteger hour;
@property (nonatomic, readwrite) NSInteger minute;
@property (nonatomic, readwrite) NSInteger second;
@property (nonatomic, copy) NSString *eventName;

@end

@implementation ItemList

@synthesize year, month, day, hour, minute, second, eventName;

@end

#import "Multitusking_LocalNotifyAppDelegate.h"

@implementation Multitusking_LocalNotifyAppDelegate

@synthesize window;

#define ItemListKey @"EVENTKEY1"
#define MessageTitleKey @"MSGKEY1"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"application: didFinishLaunchingWithOptions:");
// Override point for customization after application launch

UILocalNotification *localNotif = [launchOptions
objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if (localNotif) {
NSString *itemName = [localNotif.userInfo objectForKey:ItemListKey];
// [viewController displayItem:itemName]; // custom method
application.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1;
NSLog(@"has localNotif %@",itemName);
}
else {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *now = [NSDate date];
NSLog(@"now is %@",now);
NSDate *scheduled = [now dateByAddingTimeInterval:120] ; //get x minute after
NSCalendar *calendar = [NSCalendar currentCalendar];

unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *comp = [calendar components:unitFlags fromDate:scheduled];

NSLog(@"scheduled is %@",scheduled);

ItemList *itemList = [[ItemList alloc] init];

itemList.day = [comp day];
itemList.month = [comp month];
itemList.year = [comp year];
itemList.hour = [comp hour];
itemList.minute = [comp minute];
itemList.eventName = @"Testing Event";
// NSLog(@"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
[self scheduleNotificationWithItem:itemList interval:1];
NSLog(@"scheduleNotificationWithItem");
}
[window makeKeyAndVisible];
return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif {
NSLog(@"application: didReceiveLocalNotification:");
NSString *itemName = [notif.userInfo objectForKey:ItemListKey];
NSString *messageTitle = [notif.userInfo objectForKey:MessageTitleKey];

// NSLog(@"itemNameeeeeeeeeeeeeeeeeee%@",ToDoItemKey);
//NSLog(@"messageTitleeeeeeeeeeeeeeee %@",MessageTitleKey);

// [viewController displayItem:itemName]; // custom method
[self _showAlert:itemName withTitle:messageTitle];
NSLog(@"Receive Local Notification while the app is still running...");
NSLog(@"current notification is %@",notif);
application.applicationIconBadgeNumber = notif.applicationIconBadgeNumber-1;

}

- (void) _showAlert:(NSString*)pushmessage withTitle:(NSString*)title
{

UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:pushmessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
if (alertView) {
[alertView release];
}
}

- (void)scheduleNotificationWithItem:(ItemList *)item interval:(int)minutesBefore {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)];
NSLog(@"fireDate is %@",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];

localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i minutes.", nil),
item.eventName, minutesBefore];
localNotif.alertAction = NSLocalizedString(@"View Details", nil);

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:item.eventName,ItemListKey, @"Local Push received while running", MessageTitleKey, nil];
localNotif.userInfo = infoDict;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
[localNotif release];
}

- (NSString *) checkForIncomingChat {
return @"javacom";
};

- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Application entered background state.");
// UIBackgroundTaskIdentifier bgTask is instance variable
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);

bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];

dispatch_async(dispatch_get_main_queue(), ^{
while ([application backgroundTimeRemaining] > 1.0) {
NSString *friend = [self checkForIncomingChat];
if (friend) {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif) {
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(@"%@ has a message for you.", nil), friend];
localNotif.alertAction = NSLocalizedString(@"Read Msg", nil);
localNotif.soundName = @"alarmsound.caf";
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Your Background Task works",ItemListKey, @"Message from javacom", MessageTitleKey, nil];
localNotif.userInfo = infoDict;
[application presentLocalNotificationNow:localNotif];
[localNotif release];
friend = nil;
break;
}
}
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}

 

 

Step 5: Now compile and run the application in the Simulator.

You can Download SourceCode from here Multitusking_LocalNotify

Leave a Comment:

9 comments
Mark says August 31, 2010

Hi,

Great tutorial! only one question.. hoop you can help me..
How can i fire a daily local notification?

Thanks in advance!

Reply
Mark says September 3, 2010

Hi,

Great tutorial! only one question.. hoop you can help me..
How can i fire a daily local notification?

Thanks in advance!

Reply
Sushant says September 6, 2010

In our application, we are set time for notification every after 1 mins . So if you want to change the notification time then you need to change the interval time.

Hope this will help you. If you have any quires then please let us know.

Reply
Kish says November 12, 2010

Hi,
Can some one guide me how my iPad project. In my project I need to play audio and video files from HTML in Xcode iPad project?

Could you please give me any references to the sample code also.

Thanks & Regards,
mnkb

Reply
Edward says November 30, 2010

Hi,

Excellent article! Very well explained.

Is there a way to display a notification say every 4 hours?

How?

Thanks in advance!

Reply
    vishy says February 4, 2011

    @Edward: You can display notification after every 4 hours. You need to change interval time.

    Reply
Sumesh says February 4, 2011

You are right very excellent blog ..thank you

Reply
karthik says March 18, 2011

Thanks dude! you rock! keep posting dude!

Reply
balabrahmaiah says June 7, 2012

I create a one tableview and textview and one button, when i enter the text in text view and tuch the button.

Reply
Add Your Reply