Local Notification Issue? - iphone

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.

Related

Is it possible to have two local notification in app

I wanted to have two local notification ,both have different time ,let say my first notification will give alert after 1 minute and the second will give alert after 2 minutes.
I have tried it to create two in appDelegate but only first one is giving me the notification and not the second one .
How can I achieve this ?
Yes It is Possible to set two LocalNotification in any iOS Application
See below method by which you can set multiple LocalNotifications
You just Need to pass required parameter to this method.
- (void)setAlarmFor:(NSArray*)datesArray forTime:(NSString*)atTime notificationName:(NSString*)name
{
for(int dayIndex=0;dayIndex <[datesArray count];dayIndex++)
{
Class cls = NSClassFromString(#"UILocalNotification");//
if (cls != nil) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
NSString* dateStr=[datesArray objectAtIndex:dayIndex];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *tempDate = [dateFormatter dateFromString:dateStr];
NSString *tempString = [dateFormatter stringFromDate:tempDate];
tempString = [NSString stringWithFormat:#"%# %#",tempString,atTime];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSDate *firetAtThisDate = [dateFormatter dateFromString:tempString];
UILocalNotification *localNotif = [[cls alloc] init];
localNotif.fireDate =firetAtThisDate;//here set the Date at which mnotification fire;
NSLog(#"Notification date is:%#",firetAtThisDate);
localNotif.alertBody =name;
localNotif.alertAction = #"Your'Alert message";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
NSDictionary *userDict = [NSDictionary dictionaryWithObject:tempString
forKey:tempString];//by using this we can further cancel the Notification
localNotif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[dateFormatter release];
}
}
}
And In Appdelegate Class Prepare Action what you want as Notification Fire
//This Below Line will goes to the Appdelegate DidFinishLaunching Method
Class cls = NSClassFromString(#"UILocalNotification");
if (cls)
{
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
//do what you want
}
}
application.applicationIconBadgeNumber = 0;
//End of Appdelegate DidFinishLaunching Method.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
//do what you want
}
sure , you use one or more local notifications in your app. try this code in your project
-(void) setLocalNotification
{
NSTimeInterval todayTimeIntervel=[[NSDate date]timeIntervalSince1970];
NSTimeInterval nextOneMinTimeIntervel;
nextOneMinTimeIntervel = todayTimeIntervel + 60 ;
NSTimeInterval nexttwoMinTimeIntervel;
nexttwoMinTimeIntervel = todayTimeIntervel + 60*3;
NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:nextOneMinTimeIntervel];
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:nexttwoMinTimeIntervel];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSString *strDate1 = [dateFormat stringFromDate:date1];
NSString *strDate2 = [dateFormat stringFromDate:date2];
NSArray *arr = [NSArray arrayWithObjects:strDate1,strDate2, nil];
NSArray *titleArr = [NSArray arrayWithObjects:#"First LocalNotification",#"Second LocalNotification", nil];
for (int i =0; i < 2; i++)
{
NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithObjectsAndKeys:[arr objectAtIndex:i],#"dateStr",[titleArr objectAtIndex:i],#"title", nil];
[self scheduleLocalNotification:dic];
}
}
-(void) scheduleLocalNotification:(NSMutableDictionary*) dic
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSLog(#"%#", [dateFormat dateFromString:[dic objectForKey:#"dateStr"]]);
localNotif.fireDate = [dateFormat dateFromString:[dic objectForKey:#"dateStr"]];
localNotif.timeZone = [NSTimeZone systemTimeZone];
localNotif.alertAction = #"View";
localNotif.alertBody = [dic objectForKey:#"title"];
localNotif.userInfo = dic;
NSLog(#"value of infoDic %#",dic);
localNotif.repeatInterval = NSDayCalendarUnit;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
// get app instance
UIApplication *app = [UIApplication sharedApplication];
// create local notif
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
if (notification) {
NSDate *oneMinuteFromNow = [[NSDate date] dateByAddingTimeInterval:60];
notification.fireDate = oneMinuteFromNow;
notification.timeZone = [NSTimeZone defaultTimeZone];
NSString *notificationMessage = #"First";
notification.alertBody = notificationMessage;
notification.soundName = UILocalNotificationDefaultSoundName;
// schedule notification
[app scheduleLocalNotification:notification];
// fire notification right away
[app presentLocalNotificationNow:notification];
}
UILocalNotification *notification1 = [[[UILocalNotification alloc] init] autorelease];
if (notification1) {
NSDate *oneMinuteFromNow1 = [[NSDate date] dateByAddingTimeInterval:120];
notification1.fireDate = oneMinuteFromNow1;
notification1.timeZone = [NSTimeZone defaultTimeZone];
NSString *notificationMessage1 = #"Second";
notification1.alertBody = notificationMessage1;
notification1.soundName = UILocalNotificationDefaultSoundName;
// schedule notification
[app scheduleLocalNotification:notification1];
// fire notification right away
[app presentLocalNotificationNow:notification1];
}
By writing this you ll get one notification after 1min and second one after 2 min. In "didReceiveLocalNotification" method you can check the notification type and can show alert msg.
Hope this will help you.
Yes you can use the multiple local notification in your application.
Check this link.
Hope it helpfull for you

Local Notification issues in iOS

I am setting local notifications, for a particular date and time, for some rows in my table. So consider
case 1: When the user is setting the local notifications for first time, he selects the date from date picker, which, I pass it to the local notification object firedate.
NSArray *notificationarray = [[UIApplication sharedApplication]scheduledLocalNotifications];
if([notificationarray count]== 0)
{
m_alarmLocalNotification = [[UILocalNotification alloc] init];
m_alarmLocalNotification.fireDate = DateTime;
m_alarmLocalNotification.timeZone = [NSTimeZone defaultTimeZone];
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:m_Name forKey:#"ID"];
m_alarmLocalNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:m_alarmLocalNotification];
case2: Modifying the local notiification date.
NSArray *notificationarray = [[UIApplication sharedApplication]scheduledLocalNotifications];
for (int i = 0;i < [notificationarray count];i++)
{
UILocalNotification *notificationObject=[notificationarray objectAtIndex:i];
NSString *Name=[notificationObject.userInfo valueForKey:#"ID"];
if(Name isEqualToString:m_Name])
{
[[UIApplication sharedApplication] cancelLocalNotification:notificationObject];
m_alarmLocalNotification = [[UILocalNotification alloc] init];
m_alarmLocalNotification.fireDate = DateTime;
m_alarmLocalNotification.timeZone = [NSTimeZone defaultTimeZone];
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:m_noteName forKey:#"ID"];
m_alarmLocalNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:m_alarmLocalNotification];
}
else
{
m_alarmLocalNotification = [[UILocalNotification alloc] init];
m_alarmLocalNotification.fireDate = DateTime;
m_alarmLocalNotification.timeZone = [NSTimeZone defaultTimeZone];
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:m_noteName forKey:#"ID"];
m_alarmLocalNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:m_alarmLocalNotification];
}
}
Case 3: deleting the local notiification.
NSArray *notificationarray = [[UIApplication sharedApplication]scheduledLocalNotifications];
NSLog(#"notification count:%d",[notificationarray count]);
for (int i = 0;i < [notificationarray count];i++)
{
UILocalNotification *notificationObject=[notificationarray objectAtIndex:i];
NSString *Name=[notificationObject.userInfo valueForKey:#"ID"];
if([Name isEqualToString:m_Name])
{
[[UIApplication sharedApplication] cancelLocalNotification:notificationObject];
}
}
Problems faced.
0) I am not sure whether I am doin it the right way.
1)The default schedulednotification array doesn't get deallocated even if I delete my app and reinstall it once again.I mean it contains some previous notifications.
2)whenever I delete my cells I want the local notification should get deleted.
Regards
Ranjit
How about the things are going if you use below code while modification of notification
NSArray *notificationarray = [[UIApplication sharedApplication] scheduledLocalNotifications];
[notificationarray enumerateObjectsUsingBlock:^(UILocalNotification *notification,NSUInteger idx, BOOL *stop) {
if ([[notification.userInfo valueForKey:#"ID"] isEqual:#""]) {
notification.fireDate = [NSDate date];
}
}];

removing Notifications

I made an app that has custom notifications, but I cant remove them no matter what I do.
[[UIApplication sharedApplication] cancelLocalNotification:[idkey objectAtIndex:indexPath.row]];
That is the code I use for removal; If I use all it works. The idkey is the correct
value, and its a number in a string, #"3" in this case.
This is a part of the saving function:
-(void) addNewNotificationWithKey:(NSString*)key {
NSLog(#"%#",key);
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [tempFormatter dateFromString:datuminura];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = description1;
notif.alertAction = #"Open";
notif.soundName = UILocalNotificationDefaultSoundName;
Is it right?
Check which notification you want to remove and use following code to cancel it.
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
[EDIT]
Add following line into your local notification to make [uid isEqualToString:uidtodelete] condition work.
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"%d",[idkey objectAtIndex:indexPath.row]] forKey:#"uid"];
notif.userInfo = infoDict;

how to set NSTimer for alarm application?

I am new in iPhone application development. Now i am developing alarm application for iPhone. In this application i am selected data from UIDataPicker. Then i applied to NSLocalNotification firedate with in alarm button action. It is working first time. Then second time agin click that button i again also working, but time also same. It is wrongly working.
Here i think i need to us NSTimer. I don't know how to use NSTimer, and also it is working background application also how to set this timer.
following developed code for alarm notification.
- (void) saveButtonAction:(id)sender {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
Resource *resourceLoader = [[Resource alloc] init];
NSDictionary *prefDic = [resourceLoader getPlistDataAsDictionary:#"preference"];
NSString *musicName;
NSDate *selectedDateTime = [[NSDate alloc]init];
if (prefDic && [prefDic objectForKey:#"alarmtime"]) {
//firstVal_textField.text = [prefDic objectForKey:#"value1"];
NSLog(#"saravanan %#",[prefDic objectForKey:#"alarmtime"]);
selectedDateTime = [prefDic objectForKey:#"alarmtime"];
NSLog(#"saravanan periyasamy %#", selectedDateTime);
musicName = [NSString stringWithFormat:#"%#%#",[prefDic objectForKey:#"alarmmusic"],#".wav" ];
}
UILocalNotification *notif = [[cls alloc] init];
//notif.fireDate = [datePicker date];
notif.fireDate = selectedDateTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Alarm";
notif.alertAction = #"Show me";
//notif.repeatInterval = 0;
//notif.soundName = UILocalNotificationDefaultSoundName;
notif.soundName = musicName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"saravanan"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
}
The set button is wired up to run a
method called
scheduleNotification in the
view controller which uses the
UILocalNotification class to
schedule a notification. The code
looks as follows:
(void )scheduleNotification
{
[reminderText resignFirstResponder];
[[ UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(# "UILocalNotification" );
if (cls != nil)
{
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [ NSTimeZone defaultTimeZone];
notif.alertBody = # "Did you forget something?" ;
notif.alertAction = # "Show me" ;
notif.soundName = UILocalNotificationDefaultSoundName ;
notif.applicationIconBadgeNumber = 1 ;
NSDictionary *userDict = [ NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[ UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}

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];
}