LocalNotification in iPhone OS4

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.

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 <UIApplicationDelegate> {
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