How to call didReceiveLocalNotification:(UILocalNotification *)notification in iPhone? - iphone

I need background process (for to call a webservice) to call didReceiveLocalNotification:(UILocalNotification *)notification once app launch state, How to do that, please help me.
Thanks in Advance
I tried this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{
if (app.applicationState == UIApplicationStateInactive )
{
NSLog(#"app not running");
}
else if(app.applicationState == UIApplicationStateActive )
{
NSLog(#"app running");
}
}

This is how I create a local notification which is scheduled at 17:00 on the day this code runs. Once it fires, the method -(void)application:didReceiveLocalNotification: will be called.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
[dateComponents setHour:17];
[dateComponents setMinute:00];
[dateComponents setSecond:00];
NSDate *notificationDate = [calendar dateFromComponents:dateComponents];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = notificationDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"blah blah blah";
localNotif.alertAction = #"Ok";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

Notification is recieved in 2 cases
In application:didFinishLaunchingWithOptions: method, if the app is
neither running nor in the background.
In application:didReceiveLocalNotification: method if the app is
either running or in background. Its almost useless to show the
alert when the app is already running. So you have to show the alert
only when the app was in background at the time the notification
fired. To know if the app is resuming from background use the
applicationWillEnterForeground: method.
l
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
// Show Alert Here
}
}

Related

Appdelegate function 'didreceivelocalnotification' is called immediately after the notification is created

I'm using UILocalNotifications in iPhone to create an alarm. Alarm is scheduled when I click a UIButton. My issue is that – application:didReceiveLocalNotification: is called when I click this button, that is when I create a local notification. But , – application:didReceiveLocalNotification: should be called only when the notification time is reached. I checked it on both simulator and device and got the same results. Can anyone help me with this...thanks in advance.
-(void)createalarm:(NSString *)datend_time:(NSString *)message//creating alarm
{
NSLog(#"created!!!!!!!!!!!!!");
NSString *datestr = datend_time;
NSString *textstr = message;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *alerttime = [formatter dateFromString:datestr];
UIApplication * app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification)
{
notification.fireDate = alerttime;
//notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = 0;
notification.alertBody = textstr;
notification.soundName = UILocalNotificationDefaultSoundName;
[app scheduleLocalNotification:notification];
[app presentLocalNotificationNow:notification];
}
}
-(void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
NSLOG(#"delegate called")
}
It is because you call
[app presentLocalNotificationNow:notification];
So it shows the notification right after you created it. Remove this line of code.
[app scheduleLocalNotification:notification]; will work just fine and will shot the notification at fireDate.
Here is an example of NSLocalnotification:
-(void) scheduleNotificationForDate: (NSDate*)date {
/* Here we cancel all previously scheduled notifications */
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
NSLog(#"Notification will be shown on: %#",localNotification.fireDate);
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = [NSString stringWithFormat:
#"Your notification message"];
localNotification.alertAction = NSLocalizedString(#"View details", nil);
/* Here we set notification sound and badge on the app's icon "-1"
means that number indicator on the badge will be decreased by one
- so there will be no badge on the icon */
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
Make sure that the date you are setting is not in the past!

Local Notification Issue?

I am new in iPhone application development. I am doing alarm application. In this application I am using local notification. I am calling notification method in done button action. Now I clicked done button means notification fired correctly. Then again clicked mean also fired, again and again press means working wrongly, but I am used notification fire date time same time. In this time completed means again user click done button means again triggered notification.
I want to fire that particular time. Can you please help me.
Here I am using this source code.
-(IBAction)doneButton
{
[self scheduledNotification];
}
-(void)scheduledNotification
{
Resource *resourceLoader = [[Resource alloc] init];
NSDictionary *prefDic = [resourceLoader getPlistDataAsDictionary:#"preference"];
if ([#"ON" isEqualToString:[prefDic objectForKey:#"alarm"]])
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
NSString *musicName;
//NSDate *selectedDateTime = [[NSDate alloc]init];
selectedDateTime = [prefDic objectForKey:#"alarmtime"];
NSLog(#"saravanan periyasamy %#", selectedDateTime);
musicName = [NSString stringWithFormat:#"%#%#",[prefDic objectForKey:#"alarmmusic"],#".wav" ];
NSLog(#"musicname %#", musicName);
NSLog(#"saravanan periyasamy123 %#", selectedDateTime);
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = selectedDateTime; /* time for fireDate*/
NSLog(#"selectedtime %#",selectedDateTime);
notif.timeZone = [NSTimeZone systemTimeZone];
notif.alertBody = #"Alarm";
notif.alertAction = #"Show me";
notif.repeatInterval = 0;
notif.soundName = musicName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"saravanan"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
Class cls = NSClassFromString(#"UILocalNotification");
if (cls) {
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
//[self.viewController showReminder:reminderText];
[self.settingViewController showReminder1:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
//[self.viewController showReminder:reminderText];
[self.settingViewController showReminder1:reminderText];
}
hi i not understand what your question but here i post my one example code for LocalNotification just compare it or use this example....
here when user click done button then call "btnGo_Clicked" method
-(IBAction)btnGo_Clicked:(id)sender{
NSLog(#"\n ----------->>Go Clicked");
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSQuarterCalendarUnit fromDate:[exdatePicker date]];
[dc setDay:dc.day - 1];
NSDate *noticeDate = [[NSCalendar currentCalendar] dateFromComponents:dc];
NSDateFormatter* dateFormatterstring = [[NSDateFormatter alloc] init];
[dateFormatterstring setDateFormat:#"dd-MM-yyyy hh:mm:ss a"];
NSString *dateString = [dateFormatterstring stringFromDate:noticeDate];
txtExpirayDate.text = dateString;
UILocalNotification *notification = [[cls alloc] init];
notification.fireDate = noticeDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = [NSString stringWithFormat:#"%# your Licence Expiry Date is Tommorow",txtLicence.text];
notification.alertAction = #"Show me";
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:txtLicence.text forKey:kRemindMeNotificationDataKey];
notification.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[notification release];
}
exdatePicker.hidden=YES;
}
do some changes and you got your output
i hope this answer help you...
:)
Remove this line if you want multiple press on button.
[[UIApplication sharedApplication] cancelAllLocalNotifications];
because its removing your all previous notifications.

UILocalNotification Object in DidFinishLaunching always nil?

I am creating a local notification for a specified date as follows
UILocalNotification *localNotify = [[UILocalNotification alloc]init];
[localNotify setFireDate:notificationDate];
[localNotify setTimeZone:[NSTimeZone localTimeZone]];
[localNotify setAlertBody:#"Daily Items Reminder"];
//[localNotify setAlertLaunchImage:#"blank_Btn"];
[localNotify setAlertAction:#"View"];
[localNotify setSoundName:UILocalNotificationDefaultSoundName];
[localNotify setApplicationIconBadgeNumber:1];
[localNotify setRepeatInterval:NSDayCalendarUnit];
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"dict"
forKey:#"key"];
localNotify.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotify];
[localNotify release];
In my ApplicationDidFinishLaunching i create an object for UILocalNotification as follows
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
NSInteger badgeNumber = notification.applicationIconBadgeNumber;
if (badgeNumber < 0)
{
notification.applicationIconBadgeNumber = 0;
}
else
{
notification.applicationIconBadgeNumber = badgeNumber - 1;
}
[self showAlertMessage:#"didFinishLaunchingWithOptions" withButtons:eOk forDelegate:self];
// open screen
}
}
After clicking on View Button when Local Notification appears the application starts, now launchOption should return the localnotification object thru the key but the it always returns nil as the alertview is not getting called??.. what am i possibly doing wrong??

iPhone Local Notifications Won't Appear [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
UILocalNotification isn't working at all
I'm writing an app that sends the user an alert through the Notification Center when an event date is approaching. But when I set the date in the date picker and close the app, the notification doesn't appear. I already enabled Push Notifications in my provisioning profiles. This is all the code in my project that deals with the notification center,This is all the code in my view controller file dealing with the date picker:
- (IBAction)dateChanged:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *selectedDate = [self.datePicker date];
[defaults setObject:selectedDate forKey:#"ImportantDatesViewController.selectedDate"];
[defaults synchronize];
}
- (void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:#"ImportantDatesViewController.selectedDate"];
if (storedDate == nil) {
storedDate = [NSDate date];
}
[self.datePicker setDate:storedDate animated:NO];
}
And this is everything in my App delegate dealing with local notifications:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm'/'dd'/'yyyy"];
NSDate *eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:#"ImportantDatesViewController.selectedDate"];
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"Event in three days!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
return YES;
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSString* pushToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"%#", pushToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(#"error: %#", error);
}
Any help is much appreciated, thank you!
following code is use for the local notification.
-(IBAction)buttonPressed:(UIButton *)button
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (!localNotification)
return;
// Current date
NSDate *date = [NSDate date];
// Add one minute to the current time
NSDate *dateToFire = [date dateByAddingTimeInterval:20];
// Set the fire date/time
[localNotification setFireDate:dateToFire];
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
// Create a payload to go along with the notification
NSArray *array = [NSArray arrayWithObjects:#"Value 1", #"Value 2", nil];
NSDictionary *data = [NSDictionary dictionaryWithObject:array forKey:#"payload"];
[localNotification setUserInfo:data];
if (button == buttonAlert || button == buttonAll)
{
// Setup alert notification
[localNotification setAlertBody:#"Incoming Local Notification" ];
[localNotification setAlertAction:#"Open App"];
[localNotification setHasAction:YES];
}
if (button == buttonBadge || button == buttonAll)
{
// Set badge notification, increment current badge value
[localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1];
}
if (button == buttonSound || button == buttonAll)
{
// Setup sound notification
[localNotification setSoundName:UILocalNotificationDefaultSoundName];
}
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

firing a local notification on everyday from time selected from picker

In my app i want to set up a local notification on everyday at a particular time.Time is the one that selected from a Time picker.Is there any method for this.Plese help me.
Just specify the firedate as the date from your UIDatePicker and NSDayCalendarUnit as the repeatinterval:
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = datePicker.date;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"This is the Alert-Body Text"];
localNotif.alertAction = #"Button-Text";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
you can set Local Notifications.
Right out of apple's sample code:
- (void)scheduleNotificationWithItem:(ToDoItem *)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 addTimeInterval:-(minutesBefore*60)];
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];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
you can set a local notification for a specific timstamp.
you have to check userinfo dictionary in applicationDidFinishedLaunching for any notification data.
you have to handle:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification