Scheduled local notifications are irregular - ios

I'm having significant trouble with my iOS local notifications. I have an app, written in Objective-C, that allows the user to pick the time the notification fires, as well as the days of the week (it should fire every week on the specified days at the specified time). I have no trouble with the time of day the notification fires, that works correctly. However, when I specify the day(s) it should fire, odd things happen. At first, they fire once, but every day rather than only the specified days. Then, after the first week, they fire every day, but not only once. Instead, they fire as many times as days are specified (so if Sunday, Monday and Tuesday are chosen, each day, the user will receive 3 consecutive notifications at the specified time).
This is the code I'm using to set up the notifications.
When the "Save" button is tapped, the first thing that happens is a clearing of all notifications, to make way for the new ones.
//cancels all notifications upon save
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Next, I use NSDate, NSCalendar and NSCalendarComponents to get the specifics for the current time, as well as the components from my UIPicker (which is used to select the time of day)
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];//get the required calendar units
Then, I get the units for the time from the UIPicker, and the actual time, also from the picker.
NSDateComponents *pickedComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];
NSDate *minuteHour = [calendar dateFromComponents:pickedComponents];
[[NSUserDefaults standardUserDefaults] setObject:minuteHour forKey:#"FireTime"];
After that, I set the text I want to show up in the notification
NSString *reminder = #"Reminder text!";
Next is the actual setup of the notification. They're all the same (with the day of the week changed, of course), so I'll just show the one for Sunday.
//sunday
UILocalNotification *localNotificationSunday = [[UILocalNotification alloc] init];
if ([sundayTempStatus isEqual:#"1"])
{
//permanently save the status
[[NSUserDefaults standardUserDefaults] setObject:#"1" forKey:#"Sunday"];
//set up notifications
//if it is past sunday, push next week
if (components.weekday > 1)
{
components.day = components.day + 7; //if already passed sunday, make it next sunday
}
//components.day = 1;
components.hour = [pickedComponents hour];
components.minute = [pickedComponents minute];
NSDate *fireDate = [calendar dateFromComponents:components];
localNotificationSunday.fireDate = fireDate;
localNotificationSunday.alertBody = reminder;
localNotificationSunday.timeZone = [NSTimeZone systemTimeZone];
localNotificationSunday.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotificationSunday];
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:#"0" forKey:#"Sunday"];
}
Any help is greatly appreciated, and if any additional info or code is needed, I'll gladly provide it.

When code becomes repetitive, it often becomes more error-prone. I've written out a simple method that should take care of the scheduling of the reminders.
- (void)scheduleNotificationForDayOfWeek:(int)dayOfWeek withPickedComponents:(NSDateComponents *)pickedComponents andReminderString:(NSString *)reminderString {
NSCalendar *calendar = [NSCalendar currentCalendar];
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:[NSDate date]];
components.hour = [pickedComponents hour];
components.minute = [pickedComponents minute];
NSDateComponents *additionalComponents = [[NSDateComponents alloc] init]; // to be added onto our date
if ([components weekday] < dayOfWeek) {
additionalComponents.day = (dayOfWeek - [components weekday]); // add the number of days until the next occurance of this weekday
} else if ([components weekday] > dayOfWeek) {
additionalComponents.day = (dayOfWeek - [components weekday] + 7); // add the number of days until the next occurance of this weekday
}
NSDate *fireDate = [calendar dateFromComponents:components];
fireDate = [calendar dateByAddingComponents:additionalComponents toDate:fireDate options:0]; // add on our days
notification.fireDate = fireDate;
notification.alertBody = reminderString;
notification.timeZone = [NSTimeZone systemTimeZone];
notification.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
What this does is actually pretty simple. Call it with a day of the week (e.g., 0 = Sunday, 1 = Monday), and it will schedule a repeating reminder for that day. I couldn't reproduce your issues in my tests with your Sunday code, so I figured that somewhere among repeating that code you must have made an error.
In this method, the fire date getting has been simplified. It uses NSDateComponents to easily get the next occurrence of that weekday. Call it like this: [self scheduleNotificationForDayOfWeek:0 withPickedComponents:pickedComponents andReminderString:#"Hello, world!"]; (which would show "Hello, world!" every Sunday at the specified components)
With this snippet, you should be able to get rid of most of the repeated statements in your code, and simplify how setting notifications is done. For me, this worked perfectly.

Related

Scheduled local notification fires every day instead of once per week

I am building an iOS app that makes use of local notifications to remind the user to complete a task, but only on the certain days (chosen by the user). The time at which the notification should fire is set by the date picker. My code is based on some code from another SO post.
Say the user would like to be reminded to complete said task on Sundays. The first thing I do is find out what the current date is, and get the correct components from it, then get the correct components from the date picker for the hour and minute.
//set up calendar and correct components
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now]; //get the required calendar units
NSDateComponents *pickedComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];
NSDate *minuteHour = [calendar dateFromComponents:pickedComponents];
[[NSUserDefaults standardUserDefaults] setObject:minuteHour forKey:#"FireTime"];
NSString *reminder = #"Don't forget to check which customers are on vacation!";
Next, the data is saved, and the notification set up. This code is the same for every day of the week, with only the day name changed.
When the tempStatus is equal to "1", the user has chosen that day as a day to remind them.
//Save data
//sunday
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if ([sundayTempStatus isEqual:#"1"])
{
//permanently save the status
[[NSUserDefaults standardUserDefaults] setObject:#"1" forKey:#"Sunday"];
//set up notifications
//if it is past sunday, push next week
if (components.weekday > 1)
{
components.weekOfYear++; //if already passed sunday, make it next sunday
}
components.hour = [pickedComponents hour];
components.minute = [pickedComponents minute];
NSDate *fireDate = [calendar dateFromComponents:components];
localNotification.fireDate = fireDate;
localNotification.alertBody = reminder;
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:#"0" forKey:#"Sunday"];
}
Thanks in advance, and I will gladly provide more information and code if necessary.

Scheduling Local Notifications

I'm working on a feature that will allow users to schedule days and a time for receiving a notification.
So far, the time and message feature is working great. Where I am stuck at is the repeat interval.
Here's what I have tried:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *formatedDate = [dateFormatter stringFromDate:self.datePicker.date];
self.currentTimeLabel.text = formatedDate;
NSDate *date = [dateFormatter dateFromString:self.currentTimeLabel.text];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
[components setHour:hour];
[components setMinute:minute];
if ([self.currentRepeatLabel.text containsString:#"Sun"]) {
[components setWeekday:0];
self.notification = [[UILocalNotification alloc] init];
self.notification.fireDate = [calendar dateFromComponents:components];
self.notification.repeatInterval = NSCalendarUnitDay;
[self.notification setAlertBody:[NSString stringWithFormat:#"A friendly reminder: %#", self.titleStringToDisplay]];
if (self.soundSwitch.isOn == YES) {
self.notification.soundName = #"soundeffect.wav";
}
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:self.titleStringToDisplay forKey:#"title"];
self.notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
if ([self.currentRepeatLabel.text containsString:#"Mon"]) {
[components setWeekday:1];
self.notification = [[UILocalNotification alloc] init];
self.notification.fireDate = [calendar dateFromComponents:components];
self.notification.repeatInterval = NSCalendarUnitDay;
[self.notification setAlertBody:[NSString stringWithFormat:#"A friendly reminder: %#", self.titleStringToDisplay]];
if (self.soundSwitch.isOn == YES) {
self.notification.soundName = #"soundeffect.wav";
}
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:self.titleStringToDisplay forKey:#"title"];
self.notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
// I'm doing this for each day.
NSCalendarUnitDay is repeating my notification everyday, not matter what days I have selected. I have tried NSCalendarUnitWeekOfYear but my notifications never fire when using that.
The goal is for the user to set their title, time, and repeat days (much like the native alarm app).
How do I set the repeat interval for this?
Update and new issue:
I am using NSCalendarUnitWeekOfYear now.
Here's my issue ... the notification is no longer firing now and the repeatInterval is always set to Monday instead of the day of the week that it steps through in code.
There are several ways to do that . You can use NScalender to find the weekday and than calculate that date on which you want to be notifications fire.
-(void) calculateweeknumber
{
NSCalendar *numberCalendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [numberCalendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
[comps setSecond:0.0];
weekday = [comps weekday];
NSLog(#"number is %d",weekday);
}
Your code has many problems.
Your date comes from a UIDatePicker obviously. You should use this date. Converting it back and forth is nonsense.
Also, get rid of all that duplicated code. It makes understanding (and fixing) the code more difficult. It hides the logic.
The real problem though is that you just set date components as if it were a date. It is not. You are starting with some date thrown into components, and then setting a weekday. This will not give another valid date - why should it? How could it? What should it adjust? The day? The month? The year? Into the future or into the past? The weekday seems to be simply ignored when converting to a date.
You need to calculate a proper date (this answer describes calculating the next monday).

NSNotifications For A Date In The Past

I am coding an app that has a lot of dates that are based in the past. For instance, an anniversary date. Let's say this date is December 25th, 2000.
The user picks this date from a date picker and then the date is saved to the user's device. (so imagine the date saved is December 25th, 2000)
While thinking of how I was going to code the NSNotifications, I realized my biggest task (now seeming impossible) is how will I be able to send the user a reminder of a date that is in the future but based on a date in the past.
Example:
Anniversary date is December 25th, 2000
Remind User Every Year of December 25th.
I imagine that there must be a way, but my searches have come up empty handed.
Not sure what language you are using, but basic logic here is once user selected a date, setup a local notification for the closes date, then set the repeat to kCFCalendarUnitYear
Example code in objective-C
-(void)setAlert:(NSDate *)date{
//Note date here is the closest anniversary date in future you need to determine first
UILocalNotification *localNotif = [[UILocalNotification alloc]init];
localNotif.fireDate = date;
localNotif.alertBody = #"Some text here...";
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatInterval = kCFCalendarUnitYear; //repeat yearly
//other customization for the notification, for example attach some info using
//localNotif.userInfo = #{#"id":#"some Identifier to look for more detail, etc."};
[[UIApplication sharedApplication]scheduleLocalNotification:localNotif];
}
Once you setup the alert and the alert fired, you can handle the notification in the AppDelegate.m file by implementing
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler{
//handling notification code here.
}
Edit:
For how to get the closest date, you can implemented a method to do that
-(NSDate *) closestNextAnniversary:(NSDate *)selectedDate {
// selectedDate is the old date you just selected, the idea is extract the month and day component of that date, append it to the current year, if that date is after today, then that's the date you want, otherwise, add the year component by 1 to get the date in next year
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:selectedDate];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:selectedDate];
NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
NSDate *targetDate = [calendar dateFromComponents:components];
// now if the target date is after today, then return it, else add one year
// special case for Feb 29th, see comments below
// your code to handle Feb 29th case.
if ([targetDate timeIntervalSinceDate:[NSDate date]]>0) return targetDate;
[components setYear:++year];
return [calendar dateFromComponents:components];
}
One thing you need to think is how to treat the February 29th, do you want to alarm every year at Feb. 28th (non leap year), or do you want alarm every four years? Then you need to implement your own logic.

How can I log the day used for local notification?

I'm trying to log the day but not the date that my notification will fire at.
say I have this code that I need it to fire on Sunday, here is what I tried and what came out after that:
-(void) Sunday { // 9th Notification Every 1:35
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:[NSDate date]];
components.weekday = 1;
components.hour = 22;
components.minute = 38;
components.second = 25;
NSDate *fire = [calendar dateFromComponents:components];
NSLog(#"The Fire day is:: %#", fire);
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
notif.fireDate = fire;
notif.repeatInterval= NSWeekCalendarUnit ;
notif.soundName = #"ring.wav";
notif.alertBody = [NSString stringWithFormat: #"THANKS for Your HELP :)"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}
and the log shows:
2014-01-19 22:37:45.470 daily notification test[15595:c07] The Fire day is:: 0001-01-21 22:38:25 +0000
I'm just trying to fire a notification every specific day of the week regardless of the month and the year.. but it only works with me when defining the hour only and using the NSHourCalendarUnit.
I appreciate your help.
It would appear to not be working because you aren't setting the year, so it's defaulting to 0001. Don't just take NSWeekCalendarUnit from the current date, take the year too.

iOS set local notification on a specific day

I am sure this question is duplicated somewhere, but I can't find a solution. I am making an app in which one feature allows the user to select the days and times they will receive a local notification.
They can select any time of the day they like, and can toggle the different days of the week (mon, tues, weds etc). The notifications will be sent weekly. I therefore limit the user to creating just 3 notifications - if all 7 days are selected I will set the repeatInterval to daily (one notification). If 6 days are selected for each 3 notifications then I will need an individual notification for each day (totalling 3x6=18 notifications). In all likelihood, only 1 notification will be used so this is fine.
I know how to set an notification for a certain time in the future, but how do I set a notification for say 6pm on a Monday?
Below is my code which I have been using for testing. It sets an alert for 4 seconds in the future (I was calling it from applicationDidEnterBackground).
NSDateComponents *changeComponent = [[NSDateComponents alloc] init];
changeComponent.second = 4;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *itemDate = [theCalendar dateByAddingComponents:changeComponent toDate:[NSDate date] options:0];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatInterval = NSWeekdayCalendarUnit;
Exactly the same way you are doing right now, but create a date differently:
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:2013];
[comps setHour:10];
[comps setMinute:10];
[comps setSecond:10];
localNotif.fireDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
I have also searched about it. Below code work good for me. Pass the week day value 1 to 7 Sunday to Saturday and notification body with action which you want to fire and specify your date then notification will come on that specific day.Hope this help you.
-(void) weekEndNotificationOnWeekday: (int)weekday :(UILocalNotification *)notification : (NSDate*) alramDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: alramDate];
[componentsForFireDate setWeekday: weekday] ; //for fixing Sunday
// [componentsForFireDate setHour: 20] ; //for fixing 8PM hour
// [componentsForFireDate setMinute:0] ;
// [componentsForFireDate setSecond:0] ;
notification.repeatInterval = NSWeekCalendarUnit;
notification.fireDate=[calendar dateFromComponents:componentsForFireDate];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
I know how to set an notification for a certain time in the future,
but how do I set a notification for say 6pm on a Monday?
You can create an NSDate object representing 6pm on the next Monday with the approach showed in How to Get an NSDate for a Specific Day of Week and Time from an Existing NSDate. Then, if you want it to repeat on every Monday you can use localNotification.repeatInterval = NSWeekCalendarUnit. However I'm not sure it's going to work as expected with Daylight saving time.
I don't think you can schedule notifications with that much flexibility. Just schedule the next one anytime they change it, and when it fires schedule the next one coming up. Only one to worry about canceling and easy to setup.

Resources