local notification generating multiple notifications at the same time - ios

Sometimes local notification is generating multiple notifications for a single event number is 10. However I'm not getting in testing it's a rare case.
Is there any issue with a particular OS version ??
code is here
-(void)startLocalNotification:(NSDate *)notificationDate startTimeOfShift:(NSString *)startTime {
NSLog(#"startLocalNotification");
NSDateFormatter *newDateFormatter =[[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *startDateStr =[newDateFormatter stringFromDate:notificationDate];
NSString *scheduleDateTimeString =[NSString stringWithFormat:#"%# %#:00.000",startDateStr,startTime];
NSLog(#"scheduleDateTimeString :%#",scheduleDateTimeString);
NSDate *setFireDate,*notificationScheduledDateAndTime,*currentDate;
[newDateFormatter setDateFormat:#"dd/MM/yyyy HH:mm:ss.SSS"];
notificationScheduledDateAndTime =[newDateFormatter dateFromString:scheduleDateTimeString];
setFireDate =[notificationScheduledDateAndTime dateByAddingTimeInterval:-60*15];
currentDate =[NSDate date];
// NSTimeInterval distanceBetweenDates = [notificationScheduledDateAndTime timeIntervalSinceDate:[NSDate date]];
// NSLog(#"distanceBetweenDates :%f",distanceBetweenDates);
NSLog(#"Current Date :%# setFireDate :%#",currentDate,setFireDate);
if(counts > 15){
doNotShowNotificationAlert = NO;
}
switch ([currentDate compare:setFireDate]){
case NSOrderedAscending: {
NSLog(#"NSOrderedAscending");
}
case NSOrderedSame: {
NSLog(#"NSOrderedSame");
if(doNotShowNotificationAlert == NO){
notification = [[UILocalNotification alloc] init];
notification.fireDate = setFireDate;
NSLog(#"setFireDate :%#",setFireDate);
notification.alertBody = #"Shift Start Alert!! 15 mins to go.";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"100" forKey:#"notificationID"];
notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
NSLog(#"info Dict :%#",infoDict);
doNotShowNotificationAlert = YES;
}
break;
}
case NSOrderedDescending: {
NSLog(#"NSOrderedDescending");
break;
}
}
}

Related

Set Local Notification from Selecting Table cell

Actually This question has been asked so many Times. But I have Confusion Among those. I have tried this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
Where cell is object of UITableviewCell, But There is Not any Type of Notification. I know there is a little Bug , please help me to find out.
Place the last line as [[UIApplication sharedApplication] scheduleLocalNotification:reminderNote]; after reminderNote.fireDate line.
log the reminderNote.fireDate and check the format.
Hope this helps.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
}
You can add the local notifications upto 64 at single time.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSDate *newDate = [fireDate dateByAddingTimeInterval:(6*60*60)];
// 6*60*60=6 hour*60 minutes*60 seconds
// [fireDate dateByAddingTimeInterval:(6*60*60*i)];
localNotification.fireDate = newDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = 0;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
localNotification.alertLaunchImage = launchImage;
localNotification.applicationIconBadgeNumber = 1;
localNotification.userInfo = userInfo;
// NSLog(#"%#", [localNotification description]);
// Schedule it with the app
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
If you want to keep all the objects of NSNotification, then you need to store that somewhere. i.e in Array.
You can also use following methods for NSNotifications operation.
- (void)cancelLocalNotification:(UILocalNotification *)notification
- (void)cancelAllLocalNotifications
Make sure you are receiving notifications on
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
As a good practice prior to use the object, make sure you have initialized and set all the values to particular object.
please try this for local notification
-(void)localnotification{
NSDate *pickerDate = [self.datepicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.labelname.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

UILocalNotification applicationIconBadgeNumber not work when a day goes

Everything works fine with the following code if it is not change the day. But when change the day puts the badge 2 instead to put 1.
You know why this happens?
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = startDate;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [NSString stringWithFormat:#"%# '%#'.", NSLocalizedString (#"Tiene tareas pendientes para realizar en su acuario", ""), descripcionAcuario];
localNotification.alertAction = descripcionTextField.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSDictionary *inventory = #{
#"AcuarioID" : [NSNumber numberWithInt: acuarioSeleccionadoID],
#"TareaID" : [NSNumber numberWithInt: tareaSeleccionada],
};
localNotification.userInfo= inventory;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *alarmTimeStr = [[NSString alloc]init];
alarmTimeStr = [NSString stringWithFormat:#"%#",alarmTimeTextField.text];
NSDate *pickerdate = dateTimePicker.date;
[[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
startDate:&pickerdate
interval:NULL
forDate:pickerdate];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
pickerDate1 = pickerdate;
finaldate =pickerDate1;
// ** Local notification Assignment **
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = pickerDate1;
localNotification.alertBody = alarmNameTextField.text;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self setalarm];
-(void)setalarm
{
if ([sunValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:1];
[self setweek];
}
if ([monValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:2];
[self setweek];
}
if ([tueValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:3];
[self setweek];
}
if ([wedValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:4];
[self setweek];
}
if ([thuValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:5];
[self setweek];
}
if ([friValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:6];
[self setweek];
}
if ([satValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:7];
[self setweek];
}
alarmArray = [[DBManager sharedDatabase] getAlarmsDetail];
if ([alarmArray count] != 0)
{
[self showAllAlarmsInAlarmView];
}
if ([alarmArray count]==0)
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
}
-(void)setweek
{
#try
{
NSDateFormatter *formatterdate=[[NSDateFormatter alloc]init];
[formatterdate setDateFormat:#"YYYY-MM-dd"];
NSDateFormatter *formattertime =[[NSDateFormatter alloc]init];
[formattertime setDateFormat:#"HH:mm:ss"];
NSString * stringdate = [NSString stringWithFormat:#"%#",resultDate];
NSString *stringdate123 =[stringdate substringToIndex:10];
NSString *stringtime =[dateFormatter stringFromDate:pickerDate1];
NSString * stringtime123 =[stringtime substringFromIndex:11];
NSString * stringdate1234=[stringdate123 stringByAppendingString:#" "];
NSString * stringdate12345=[stringdate1234 stringByAppendingString:stringtime123];
finaldate =[dateFormatter dateFromString:stringdate12345];
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = finaldate;
localNotification.alertBody = alarmNameTextField.text;
localNotification.repeatInterval =NSWeekCalendarUnit;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];//#"Jai Hanuman.mp3";
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
#catch (NSException *exception)
{
[[saveClass shared_class] writeStringToFile:#"alarmViewController" andfunctionname:#"saveAlarmAndSetNotification" andexception:(NSString*)exception];
}
#finally
{}
}
-(NSDate *) getDateOfSpecificDay:(NSInteger ) day /// here day will be 1 or 2.. or 7
{
NSInteger desiredWeekday = day;
NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:finaldate];
NSLog(#"%#",[NSDate date]);
NSInteger currentWeekday = dateComponents.weekday;
if (desiredWeekday == currentWeekday)
{
differenceDays = 7;
daysComponents = [[NSDateComponents alloc] init];
}
else
{
differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
daysComponents = [[NSDateComponents alloc] init];
}
daysComponents.day = differenceDays;
resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:finaldate options:0];
return resultDate;
}

Repeat Functionality in Alarm

I am new to iOS. I am making an alarm application and I want to implement the repeat functionality. I search a lot and didn't understand much how to do this. I know it is done by notification method. I am stuck with it . Please anyone tell me the solution. Here is my code when user save the alarm.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
NSLog(#"dateformater %#",dateFormatter);
dateFormatter.timeStyle = NSDateFormatterShortStyle;
NSString * dateTimeString = [dateFormatter stringFromDate:timePicker.date];
NSLog(#"date time string %#",dateTimeString);
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
//[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
datesArray = #[[dateFormatter stringFromDate:self.timePicker.date]];
NSLog(#"dates array is %#",datesArray);
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSArray * repeatDays = [repeatResult componentsSeparatedByString:#","];
for (NSString * days in repeatDays)
{
if ([days isEqualToString:#"Sun"])
{
[self getDateOfSpecificDay:1];
}
if ([days isEqualToString:#"Mon"])
{
[self getDateOfSpecificDay:2];
}
if ([days isEqualToString:#"Tue"])
{
[self getDateOfSpecificDay:3];
}
if ([days isEqualToString:#"Wed"])
{
[self getDateOfSpecificDay:4];
}
if ([days isEqualToString:#"Thu"])
{
[self getDateOfSpecificDay:5];
}
if ([days isEqualToString:#"Fri"])
{
[self getDateOfSpecificDay:6];
}
if ([days isEqualToString:#"Sat"])
{
[self getDateOfSpecificDay:7];
}
}
}];
AlarmObject * alarm = [[AlarmObject alloc] init];
alarm.repeatData = repeatResult;
alarm.clockDate = dateTimeString;
[self.delegate alarmSetting:alarm];
[self scheduleLocalNotificationWithDate:timePicker.date];
[self.navigationController popViewControllerAnimated:YES];
and here is my scheduledLocalNotification mehtod
-(void) scheduleLocalNotificationWithDate:(NSDate *)fireDate
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.alertBody = #"Time to wake Up";
localNotif.alertAction = #"Show me";
localNotif.soundName = #"Tick-tock-sound.mp3";
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSCalendarUnitWeekOfYear;
NSLog(#"%#",[NSDate date]);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];`
I'm stuck with it from past 4 days. I know my question is duplicate but I am not sure how implement that logic. Thanks in advance.
Change the
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
to
dateFormatter.timeZone = [NSTimeZone localTimeZone];
and check out this tutorial for repeat fucntionailty.

Best way to schedule many UILocalNotifications

I am trying to schedule many UILocalNotifications at the same time. I refresh a lot of data and need to cancel all previous notifications and recreate them. Currently I have this code to cancel and create the notifications:
- (void)scheduleNotifications {
NSDate *start = [NSDate date];
// Cancel old notifications
[NotificationHandler cancelNotificationsNamed:#"ScheduleNotification"];
if (self.user.scheduleNotifications.boolValue) {
for (NSInteger i = 0; i < self.user.scheduleDays.count; i++) {
ScheduleDay *day = [self.user.scheduleDays objectAtIndex:i];
for (SchedulePeriod *period in day.periods) {
if (period.desc.length > 0) {
NSDateComponents *dateComponents = [[NSCalendar autoupdatingCurrentCalendar] components:NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:[NSDate date]];
dateComponents.day += 2 + i - dateComponents.weekday;
NSArray *timeComponents = [period.startTime componentsSeparatedByString:#":"];
NSInteger hour = [[timeComponents objectAtIndex:0] integerValue];
dateComponents.hour = hour < 7 ? hour + 12 : hour; // add 12 to hour if before 7 (assume afternoon)
dateComponents.minute = [[timeComponents objectAtIndex:1] integerValue] - 5;
NSDate *fireDate = [[NSCalendar autoupdatingCurrentCalendar] dateFromComponents:dateComponents];
if ([[NSDate date] compare:fireDate] == NSOrderedDescending) {
fireDate = [fireDate dateByAddingTimeInterval:604800]; // add a week if date is passed
}
[NotificationHandler scheduleNotificationNamed:#"ScheduleNotification"
forDate:fireDate
message:period.desc
repeatWeekly:YES];
}
}
}
}
NSLog(#"%f sec", [[NSDate date] timeIntervalSinceDate:start]);
}
NotificationHandler.m:
+ (void)scheduleNotificationNamed:(NSString *)name forDate:(NSDate *)date message:(NSString *)message repeatWeekly:(BOOL)repeatWeekly {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.userInfo = #{#"kNotificationName" : name};
notification.fireDate = date;
notification.alertBody = message;
notification.timeZone = [NSTimeZone defaultTimeZone];
if (repeatWeekly) {
notification.repeatInterval = NSCalendarUnitWeekOfYear;
}
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
+ (void)cancelNotificationsNamed:(NSString *)name {
for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[[notification userInfo] objectForKey:#"kNotificationName"] isEqualToString:name]) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
}
Unfortunately it can sometimes take a few seconds to cancel and create the notifications which blocks the UI. Is there a better way?

A few questions about NSLocalNotifications

This is my localNotification codes.
NSDate *currentDate = [NSDate date];
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:currentDate];
[components setTimeZone:[NSTimeZone systemTimeZone]];
[components setHour:13];
[components setMinute:11];
[components setDay: sonOdemeGunuNumber.integerValue -3];
NSDate *test = [calendar dateFromComponents:components];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = test;
localNotification.alertBody = [NSString stringWithFormat:#"%# 3 days left.",_txtBankaAdi.text];
localNotification.alertAction = #"Show item";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
localNotification.repeatInterval = kCFCalendarUnitDay;
localNotification.repeatInterval = kCFCalendarUnitMonth;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
sonOdemeGunuNumber is ToDoItem alert day(number of current day for example -3).
if(sonOdemeGunuNumber.integerValue == currentDay.integerValue){
localNotification.repeatInterval = nil; }
I wanted to notify user 3 days earlier and it should continue get alert until currentDay = sonOdemeGunuNumber.
1- If I write this if-else statement it will work ?
2- If user delete the localNotification Item in my TableView, in this case item is Bank Account ?
Bank Account localNotification will delete itself automatically ?
Thank you !
Have a nice day everyone...
I found the solution for if user delete the item in tableview i cancel deleted item's localNotification..
First of all, send ID with userInfo to the LocalNotification Center.
localNotification.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:_txtItemName.text,#"delThisNot", nil];
Secondly go and edit your tableView method.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
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 *adi = [[self.fetchedResultsController objectAtIndexPath:indexPath]valueForKey:#"odemeAdi"];
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"delThisNot"]];
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
adi = Deleting item.
uid = your item id (which is your txtItemName.text)
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
if user want to delete item name (adi) == uid (txtItemName.Text)
Cancel this notification.
Sorry for my grammers I just wanted to help other people I hope you guys can understand me :D
Thanks.

Resources