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.
Related
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.
The common question on stackoverflow is how to get the Day of Year from a date but how to you get the date from the Day of Year?
I'm using the following code to generate the Day of Year but how to I do the converse?
// Calculate Day of the Year
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
setDayOfYear = dayOfYear;
return setDayOfYear;
Assuming you know the year you want and the actual time of the date doesn't matter and you have the correct locale and time zones set up, you can just convert the day of the year and year from components back into a date. Again, you may need to decide what your application needs to do about the time component and you have to make sure that the day and year actually make sense for the calendar, but assuming the gregorian calendar you listed in your example, and the 200th day of 2013 (19 July, 2013), you could so something like this:
NSDateComponents* components = [[NSDateComponents alloc] init];
[components setDay:200];
[components setYear:2013];
NSDate* july19_2013 = [gregorian dateFromComponents:components];
If I were to run this, I'd get a date that's 19 July, 2013 # 07:00 since my current locale is in a time zone equiv of America/Los_Angeles and I didn't configure the calendar.
I'd like to group dates for a given week, with the starting day being what the user chooses in their preferences.
For example my preference may be that my work week starts on a Friday, and so Friday to Thursday should be my week.
Sunday-Saturday. Monday-Sunday, etc.
So I'd like to present the user with a date picker, and although they can pick any calendar day, I'd like to have the collection of
dates start with their starting day.
For example if I pick a random Wednesday next month, and my preferences are for a starting work week of Monday, then my collection of dates
should start at Monday. The code must be able to walk backwards 2 days, find that monday, then walk forwards until Sunday.
My strategy was to do just that - loop backwards until the start date is found and simply add 6 days to end on a Saturday.
Before I go about it this way, is there a better way (or maybe some sort of specifics in iOS that would make this easier for me than somewhere else)?
Examine the NSCalendar class. In particular is the method: setFirstWeekday:.
Example code:
NSDate *today = [NSDate date]; // Or a date of your choice
NSLog(#"today: %#", today);
NSCalendar *caledar = [NSCalendar currentCalendar];
[caledar setFirstWeekday:5]; // Sunday is 1
NSDate *beginningOfWeek;
[caledar rangeOfUnit:NSWeekCalendarUnit
startDate:&beginningOfWeek
interval:NULL
forDate:today];
NSLog(#"beginningOfWeek: %#", beginningOfWeek);
NSLog output:
today: 2014-07-22 14:45:01 +0000
beginningOfWeek: 2014-07-17 04:00:00 +0000
Have you looked at NSDateComponents? You can specify a specific day of the week.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *pickedDateComponents = [calendar components:NSCalendarUnitWeekday fromDate:pickedDate];
NSInteger saturday = 7; // In the Gregorian calendar, 1 is Sunday, 2 is Monday, etc..
NSDateComponents *daysUntilSaturdayComponents = [NSDateComponents new];
daysUntilSaturdayComponents.weekday = saturday - pickedDateComponents.weekday;
NSDate *saturdayAfterPickedDate = [calendar dateByAddingComponents:daysUntilSaturdayComponents toDate:pickedDate options:0];
I have a notification system in my app that allows users to set multiple notifications and they can be:
Daily
Weekly
Monthly
The first 2 are ok, but on the third one I have a problem.
Lets say that we are on March and the user sets the notification to trigger on the 31st of the month. The notification is scheduled correctly, but if we where on April (30 days) for example the notification is scheduled on the 1st of May.
I have 2 questions:
How can I schedule notification on the last day of the month? Or set them up to handle this case gracefully in the following months.
If the notification on the 31st of March is scheduled correctly, will the next one be scheduled on the 30th of April and then on the 31st of May? My guess is no, will be 31 of march, 1st April and 31st of April.
Scheduling multiple notification is not an option for me because apple has a limit and that limit can be reached easily if the user has 6 monthly notifications (6x12) and they could have more than that.
Thanks,
Sergio
EDIT
Sorry I didn't explained myself properly.
I don't have the problem setting the notification on the correct day. But I have a problem with how the repetitions will work. If I set a notification to trigger on the 31st every month starting on the 31st of March (lets assume we are in March) the first one will come up on the right day, but what would happen on April?
Thanks again.
You can get the last day of the month of a specific date using the below methods
-(NSDate*)lastDayOfMonthOfDate:(NSDate *)date
{
NSInteger dayCount = [self numberOfDaysInMonthCountForDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSDateComponents *comp = [calendar components:
NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit fromDate:date];
[comp setDay:dayCount];
return [calendar dateFromComponents:comp];
}
-(NSInteger)numberOfDaysInMonthCountForDate:(NSDate *)date
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:TIMEZONE]];
NSRange dayRange = [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:date];
return dayRange.length;
}
Find the last day from these method and schedule notification for that day
Source : Getting the last day of a month
-[NSCalendar rangeOfUnit:inUnit:forDate:] will tell you the minimum and maximum values that a particular date component can take in a larger component, in the context of a particular date.
If you use NSDayCalendarUnit and NSMonthCalendarUnit, the length of the result will be the last day of the month containing the passed date.
For example:
NSCalendar * c = [NSCalendar currentCalendar];
NSRange aprilRanger = [c rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[NSDate date]];
NSLog(#"%lu", aprilRanger.length);
NSDateComponents * minusTwoMonths = [NSDateComponents new];
[minusTwoMonths setMonth:-2];
NSDate * febDay = [c dateByAddingComponents:minusTwoMonths
toDate:[NSDate date]
options:0];
NSRange febRange = [c rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:febDay];
NSLog(#"%lu", febRange.length);
Produces:
30
28
And this will give you the correct answer when weird things like leap days happen, too.
What I had to do was:
Check if the current month has the day that the user requested (max 31).
If it doesnt then schedule a normal notification for the current month on the last day and then schedule the monthly one on the following month, the OS will handle the rest.
Note: If the current month doesn't have the requested day (31 of feb), the next one will definitely have it (31 of mar).
If it does then schedule the monthly on the current month.
Hey It's not a big deal.
In your notification object set repeatInterval to NSMonthCalendarUnit
UILocalNotification *notify = [ [UILocalNotification alloc] init ];
notify.fireDate = notificationDate;
notify.repeatInterval = NSMonthCalendarUnit;
// use NSDayCalendarUnit, NSWeekCalendarUnit for daily or weekly respectively.
Thanks
damithH
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.