How to notify a notification message at every month end day - ios

How to notify every month notification.
-(void)applicationDidEnterBackground:(UIApplication *)application {
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = #"dd-MM-yyyy";
NSComparisonResult result = [[format stringFromDate:[NSDate new]] compare:[format stringFromDate:[self lastDayOfMonthOfDate:[NSDate date]]]];
if (result == NSOrderedSame){
if (![USERDEFAULTS boolForKey:#"IS_MONTH"]) {
[self getNotifiedForEveryMonth:nil];
}}
else{
[USERDEFAULTS setBool:NO forKey:#"IS_MONTH"];
}
}
// getNotifiedForEveryMonth
-(void)getNotifiedForEveryMonth:(id)userinfo{
// Schedule the notification
[USERDEFAULTS setBool:YES forKey:#"IS_MONTH"];
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate date];
localNotification.alertBody = #"Every Month Notificiation";
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
}
-(NSDate*)lastDayOfMonthOfDate:(NSDate *)date
{
// NSGregorianCalendar
NSInteger dayCount = [self numberOfDaysInMonthCountForDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSDateComponents *comp = [calendar components:
NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay fromDate:date];
[comp setDay:dayCount];
return [calendar dateFromComponents:comp];
}
-(NSInteger)numberOfDaysInMonthCountForDate:(NSDate *)date
{
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:TIME_ABSOLUTE]];
NSRange dayRange = [calendar rangeOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitMonth
forDate:date];
return dayRange.length;
}
The above code with i try to notify the notification.
Its getting notification every month end day,
If user close the notification and then next month comes the notifcation is not notifying.
After installation the application, how to notify the user very month end day a notification message.
Your inputs are appreciated.

1) If you want fire notifications every month, even if user didn't open an app more then month, you should set several notifications (up to 60). For example, set notifications for next 12 month.
2) You should set notifications by this code (on loop, 12 times):
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
3) Before you set new notifications, remove old with this code:
[[UIApplication sharedApplication] cancelAllLocalNotifications];

Related

Show local notification on specific day and specific time in iOS

i want to show local notification on every saturday like this,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat=#"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:[NSDate date]] capitalizedString];
NSLog(#"day: %#", dayString);
if([dayString isEqualToString:#"Saturday"])
{
NSLog(#"Success");
[self PushNotification];
}
-(void)PushNotification
{
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertTitle = #"Test";
localNotification.alertBody =#"test of notification";
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *componentsForFireDate = [calendar components:(NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitHour | NSCalendarUnitMinute| NSCalendarUnitSecond | NSCalendarUnitWeekday) fromDate: [NSDate date]];
[componentsForFireDate setWeekday: 7]; //for fixing Saturday
[componentsForFireDate setHour: 17]; //for fixing 5PM hour
[componentsForFireDate setMinute:0];
[componentsForFireDate setSecond:0];
localNotification.repeatInterval = NSCalendarUnitWeekOfMonth;
}
but my local notification is display in every minit then how can i display notification on every Saturday of the week.
thanks.
Try to declare fireData property in localNotification and schedule your notification
localNotification.fireDate = componentsForFireDate.date;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
Hope this help

Making an Alarm application in iOS

I am making an alarm application. When I set the alarm the notification fire immediately. I set two schedule notifications functions for alarm. One is for everyday repeat alarm and other is for weekly repeat alarm. My code for everyday repeat alarm is working fine but for weekly repeat alarm , notifications fire immediately and sometimes fire at different day.
Here is code for repeat alarm for weekly basis.
-(void) scheduleLocalNotificationWithWeek:(NSDate *)fireDate
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = calculateAlarmDay;
NSLog(#"%#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone localTimeZone];
localNotif.alertBody = #"Time to wake Up";
localNotif.alertAction = #"Show me";
localNotif.soundName = #"Tick-tock-sound.mp3";
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSWeekCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
and here is a code in which I calculate the day on which it fires e.g if user select sunday than it fires on sunday 28-2-2016 and than next sunday 6-3-2016 and so on..
-(void) repeataftersevendays:(int) day
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSLog(#"%#",components);
[components setTimeZone:[NSTimeZone localTimeZone]];
[calendar setTimeZone: [NSTimeZone localTimeZone]];
finalValue = 0;
if (weekday == day)
{
finalValue=0;
}
else if (weekday < day)
{
int tempWeekDay = weekday;
while ( tempWeekDay < day )
{
tempWeekDay++;
finalValue++;
NSLog(#"%i",finalValue);
}
}
else
{
int tempDay = day;
while ( weekday >= tempDay )
{
tempDay++;
finalValue++;
}
}
calculateAlarmDay = [calendar dateByAddingUnit:NSCalendarUnitDay
value:finalValue
toDate:[NSDate date]
options:0];;
NSLog(#"value is %#",calculateAlarmDay);
}
I am stuck with this stuff from last seven days. Please tell me the solution. Thanks

Local notifications are repeat on every day and every month

I have a Local Notifications. Like this ;
NSNumberFormatter *faturaSonOdemeGunuFormatter = [[NSNumberFormatter alloc] init];
[faturaSonOdemeGunuFormatter setNumberStyle:NSNumberFormatterNoStyle];
NSNumber *faturaSonOdemeGunuNumber = [faturaSonOdemeGunuFormatter numberFromString:_txtFaturaGunu.text];
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:12];
[components setMinute:40];
[components setDay: faturaSonOdemeGunuNumber.integerValue -3];
NSDate *test = [calendar dateFromComponents:components];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = test;
localNotification.alertBody = [NSString stringWithFormat:#"%# Faturanıza 3 gün kaldı.",_txtFaturaAdi.text];
localNotification.alertAction = #"Faturayı göster";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
This code does not repeat itself.I want to repeat Local Notification every Month in faturaSonOdemeGunuNumber integerValue day.It should be start sonOdemeGunuNumber -3 (for example user writes 17. it should start 14) and it should give a notification on every day until faturaSonOdemeGunuNumber. I mean it should continue notify the users every day until selected day.
How can i do that?
Thank you!
Add this:
localNotification.repeatInterval = kCFCalendarUnitMonth; //For monthly repeats
localNotification.repeatInterval = kCFCalendarUnitDay; //For daily repeats
Try this,
notification.repeatInterval= NSDayCalendarUnit; //For day
notification.repeatInterval= NSWeekCalendarUnit; //For Week
notification.repeatInterval= NSMonthCalendarUnit; //For Month
Ref Link: http://useyourloaf.com/blog/2010/09/13/repeating-an-ios-local-notification.html

How to allocate custom time in UILocalnotification?

- (void)scheduleNotification :(int) rowNo
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.timeZone = [NSTimeZone defaultTimeZone];
NSString *descriptionBody=[[remedyArray objectAtIndex:rowNo]objectForKey:#"RemedyTxtDic"];
NSLog(#"%#",descriptionBody);
notif.alertBody = [NSString stringWithString:descriptionBody];
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:notif.alertBody
forKey:#"kRemindMeNotificationDataKey"];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
}
I have a column name frequency which is fetched from Sqldb where it contains the number of times notification should appear for a particular cell.
if frequency = 3 ..the notification should fire say 8 AM , 2PM then 8PM
if frequency = 4 ..the notification should fire say 8 AM , 12PM , 4PM then 8PM.
Is there a way to do it? If anyone can help me that would be great
Unfortunately, You can specify value for repeatInterval only of type NSCalendarUnit (day, week, month). So, I think, You need to create several Notifications with different fireDate, and specify for them repeatInterval = NSDayCalendarUnit
For example,
NSDate *currentTime = [NSDate date];
notification1.fireDate = [NSDate dateWithTimeInterval:SOME_INTERVAL sinceDate:currentTime];
notification1.repeatInterval = NSDayCalendarUnit;
notification2.fireDate = [NSDate dateWithTimeInterval:SOME_INTERVAL * 2 sinceDate:currentTime];
notification2.repeatInterval = NSDayCalendarUnit;
After user viewed some of notifications - You can cancel them.
Update.
You can also create NSDate from different components like this:
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeekday:2]; // Monday
[components setWeekdayOrdinal:1]; // The first Monday in the month
[components setMonth:5]; // May
[components setYear:2013];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:components];
Also You can set hour, minutes, seconds, timezone and other parameters.

IOS CancelNotificaion on particular date when the app is in Background

I am working on a application that reminds about the expiry date. I have implemented the same using UILocalNotification with repeat Interval (NSMonthCalendarUnit, NSDayCalendarUnit,NSDayCalendarUnit). For example I have the fire date on 01-01-2012 and the repeat interval is NSDayCalendarUnit and the end date is 12-12-2012, is it possbile to cancelLocalNotification: on expiry.
here is the code:-
- (void) scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtExpiryDate.text, #"ExpiryDate",
txtRegNo.text , #"RegNo",
nil];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.userInfo = userInfo;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
NSLog(#"Repeat Type:%#",txtRepeat.text);
if([txtRepeat.text isEqualToString:#"Every Week"])
{
NSLog(#"Every Week");
localNotification.repeatInterval = 256;
}
else if([txtRepeat.text isEqualToString:#"Every Month"])
{
NSLog(#"Every Month");
localNotification.repeatInterval = NSMonthCalendarUnit;
}
else if([txtRepeat.text isEqualToString:#"Every Day"])
{
NSLog(#"Every Day");
localNotification.repeatInterval = NSDayCalendarUnit;
}
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
NSLog(#"appDelegate.BadgeNumber:%d",appDelegate.BadgeNumber);
localNotification.alertLaunchImage = launchImage;
appDelegate.BadgeNumber = appDelegate.BadgeNumber + 1;
localNotification.applicationIconBadgeNumber = appDelegate.BadgeNumber;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
}
I have worked by comparing current date to expiry date. But this work only if the app is in foreground and i cannot cancelnotification not background for a particular date. Please find the below code for the same:-
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
BadgeNumber = 0;
application.applicationIconBadgeNumber = BadgeNumber;
NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDateFormatter *formatter =[[[NSDateFormatter alloc]init] autorelease];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"localNotifications Count %d",localNotifications.count);
for (UILocalNotification *notify in localNotifications)
{
//notify.applicationIconBadgeNumber = 0;
NSString *ExpiryDateString = [notify.userInfo objectForKey:#"ExpiryDate"];
NSDate *ExpiryDate = [formatter dateFromString:ExpiryDateString];
NSDate * NextFireDate = nil;
NSLog(#"Expiry Date:%#",ExpiryDateString);
if(notify.repeatInterval == NSDayCalendarUnit)
{
NSLog(#"Repeat Every Day");
NextFireDate = [[NSDate date] dateByAddingDays:1];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
if(notify.repeatInterval == NSWeekCalendarUnit)
{
NSLog(#"Repeat Every Day");
NextFireDate = [[NSDate date] addTimeInterval:D_WEEK];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
if(notify.repeatInterval == NSMonthCalendarUnit)
{
NSLog(#"Repeat Every Day");
//NextFireDate = [[NSDate date] addTimeInterval:D_Month];
NextFireDate = [self CalculateExipiryDateForMonth];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
NSComparisonResult result = [NextFireDate compare:ExpiryDate];
NSLog(#"NSComparisonResult:%d",result);
if(result == NSOrderedDescending)
{
NSLog(#"Cancell......... Notification");
NSLog(#"notify :::%#",notify);
}
else
{
NSLog(#"Re-Schedule Notification");
BadgeNumber = BadgeNumber + 1;
notify.applicationIconBadgeNumber = BadgeNumber;
NSLog(#"BadgeNumber:%d",BadgeNumber);
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
}
}
}
-(NSDate*) CalculateExipiryDateForMonth
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];
NSDate *expiryDay = [gregorian dateFromComponents:nextMonthComponents];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = -1;
NSDate *NewExpiry = [gregorian dateByAddingComponents:dayComponent toDate:expiryDay options:0];
[gregorian release];
[dayComponent release];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"Next Exipiry Date -----:%#",[formatter stringFromDate:NewExpiry]);
return NewExpiry;
}
In short, no, you cannot cancel a UILocalNotification while your app is running in the background.
**Apple RESPONSE:-**
I'm responding to your question about UILocalNotification.
At this time UILocalNotification does not have a way to specify an expiry
date or number of repetitions before the notification is automatically
canceled.
The closest you can get today is to schedule up to 64 individual
notifications instead of using the repeat interval.
But you're correct; if the user doesn't ever bring your app to the
foreground, it won't have the opportunity to cancel or reschedule local
notifications.
I highly recommend that you file an enhancement request at <
https://developer.apple.com/bugreporter> asking for this functionality in a
future release of iOS.
You also asked about what happens to local notifications when the user
removes your app from the device. iOS stores the local notifications so
that they are still scheduled if the user deletes and then reinstalls the
app.
When your app runs, it can check the scheduledLocalNotifications property
of UIApplication and remove any notifications that are no longer relevant.
Best regards,
--gc
Garth Cummings
Apple Developer Technical Support

Resources