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
Related
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.
I wonder if there is a way to know how each day of a week ordered? I know in the Gregorian calendar, property 'weekday' indicates 1-7, and
Sunday is represented by 1. But when I change the region(setting->General->Language &Region->Region) to Russia, the Apple's calendar app displays 'M'as the first day of a week, while United States displays 'S' as the first day of a week.
How can I work out this programmatically? Any idea, thanks advance.
Try this
[[NSCalendar currentCalendar] firstWeekday]
you can set programmatically start day of week by following code.
To get first day of week after setting
- (NSDate*)firstDayOfWeek
{
NSCalendar* calender = [[NSCalendar currentCalendar] copy];
[calender setFirstWeekday:2]; //Override locale to make week start on Monday
NSDate* startOfTheWeek;
NSTimeInterval interval;
[calender rangeOfUnit:NSWeekCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:self];
return startOfTheWeek;
}
To set First day of week
[[NSCalendar currentCalendar] setFirstWeekday:2]; //Override locale to make week start on Monday
NSCalendar has a property named firstWeekday which indicates the index of the first weekday of the receiver.
NSCalendar documentation
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 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.
I an using the current methods to get the first and the last day of the current week:
NSDate *weekDate = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:weekDate];
[currentComps setWeekday:1]; // 1: sunday
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:7]; // 7: saturday
NSDate *lastDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
This was working perfect, but now in ios 4.3 and it's not working.
Any idea what can be the problem?
I have started Xcode 4.1 on my OS X 10.6 partition and tried to compile your code against the iOS 4.3 SDK. It turned out that NSWeekOfYearCalendarUnit is undefined, so that must have been introduced in later iOS versions. This might explain why it does not work on iOS 4.3.
The following alternative code works and gives the correct result:
NSDate *now = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *firstDayOfTheWeek;
NSTimeInterval length;
[myCalendar rangeOfUnit:NSWeekCalendarUnit
startDate:&firstDayOfTheWeek
interval:&length
forDate:now];
NSDate *lastDayOfTheWeek = [firstDayOfTheWeek dateByAddingTimeInterval:length];
Update: The above code gives the (start of) the first day in the week and the (start of) the next week. If you add (length - 1) instead of length then you will get the end of the last day in the week (thanks #rmaddy!). Alternatively, you can add 6 days to the first day:
NSDate *now = [NSDate date];
NSDate *firstDayOfTheWeek;
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[myCalendar rangeOfUnit:NSWeekCalendarUnit
startDate:&firstDayOfTheWeek
interval:NULL
forDate:now];
NSDateComponents *sixDays = [[NSDateComponents alloc] init];
[sixDays setDay:6];
NSDate *lastDayOfTheWeek = [myCalendar dateByAddingComponents:sixDays toDate:firstDayOfTheWeek options:0];
Remark: This code also handles the "start of week" correctly according to the locale.
Your third component, NSWeekOfYearCalendarUnit, is only available as of iOS 5. See https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html. I believe for what you are doing, you don't need that component, you should be able to just remove it.
As for the localization comments from the others on this post, they are correct that things change in different locales, but not the way you might expect. Sunday is indeed always day 1 (and Saturday day 7), but in cultures where Monday is the first day of the week, your code will return the following Saturday and the following Sunday, seemingly at the end of the week. You can fix this by explicitly setting your calendar to use the en-US locale, or attempt to account for other locales by using the firstDayOfWeek property. You can test this by switching the Region Format of you simulator to German > Germany, in Settings > General > International > Region Format.
It's unclear in which sense you are having difficulties, but it might be simply that there's no consensus on which is the first day of the week.
[old example redacted; Mike below correctly pointed out that it was invalid]
Per the NSDateComponents documentation, "For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1."; if your device is using any of the nine other calendars supported by iOS — such as the Buddhist, Chinese or Hebrew calendars — then Apple doesn't guarantee that Sunday is day 1.