Error in Notification Part - ios

I am working with the notification part of the project, in this I want the sound notification which will notify the user about the activity. The code I am working with is below:
-(void) scheduleNotificationForDate {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateParts = [[NSDateComponents alloc] init];
[dateParts setHour:18];
[dateParts setMinute:20];
[dateParts setSecond:00];
NSDate *sDate = [calendar dateFromComponents:dateParts];
NSLog(#"date : %#", sDate);
localNotif.fireDate = sDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.alertBody = #"Hello Testing";
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(#"notification started");
}
With the help of this code I am getting the written notification on my device but I don't hear any alert sound when notification is alerted.
Please have a look on the code and try to locate my error. Your help will be much appreciable.

Look at your console.
date : 0001-01-01 17:26:32 +0000
You have scheduled the notification ~2000 years in the past, because you didn't specify components for year, month and day. Setting a fireDate that is in the past means the notification is delivered immediately.
If you want to schedule a notification for today at 18:30 you could do something like this:
// get year, month and day components from current time
NSDateComponents *dateParts = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[dateParts setHour:18];
[dateParts setMinute:20];
[dateParts setSecond:00];

May be you have notification sound for this app disabled in Settings/Notification Center?

If your app is in active state it will not give alert sound, put it in background and test it.
NOTE: make sure your system volume is on .

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.

How to notify a notification message at every month end day

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];

How to set UILocalNotification for 30 consecutive days

I want to schedule UILocalNotificaion for 30 consecutive days at 8:00 AM daily and i want to implement that functionality with one UILocationNotification instance only. Here is my code to schedule local notification.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:#"08:00"];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
localNotification.timeZone=[NSTimeZone defaultTimeZone];
localNotification.alertBody = #"You just received a local notification";
localNotification.alertAction = #"View Details";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[formatter release];
[date release];
It will fire daily notifications forever at 08:00AM, but i want to be notified for 30 consecutive days only. The easiest solution is to fire 30 UILocalNotifications but i want to do that with 1 UILocalNotification instance. How can i do that? Please help.
In UILocalNotification userInfo property save NSDate object when you create Notification.
When you open Notification,
check with the current date with date in userinfo . If there is difference is more than 30 days you can cancel your local notification.
NSDate *now = [NSDate date];
// now a NSDate object for now + 30 days
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:30];
NSDate *endDate = [gregorian dateByAddingComponents:offsetComponents toDate:now options:0];
After that check:
if([currentDate isEarlierDate:endDate]){
//Fire the notification
}

How to schedule more local notifications in iOS when notification crosses limit of 64 [duplicate]

This question already has answers here:
Schedule number of Local Notifications
(6 answers)
Closed 7 years ago.
I am developing a calendar app which consists of multiple events(e.g 500 events) which consists of birthdays.I am downloading events form web service. I want to give user the alert on each birthdate at a specific time sat 10:00 AM on the birthday. I am using local notification for scheduling a alert but I am stuck as iOS allows only 64 notifications per app and I have multiple birthdays. I don't know how to schedule more notifications once the app crosses the limit. Please suggest how would I solve this problem. below is my code to schedule notifications
- (void)scheduleNotification:(NSMutableArray *)datesArray withMessage:(NSMutableArray *)messagesArray NotificationID:(NSString *)notificationID
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setDateFormat:#"dd/MM/yyyy"];
// NSDate *myTime = [formatter dateFromString:#"06:10 PM"];
NSDate *myTime = [formatter dateFromString:fireTime];
for (int i = 0; i < [datesArray count]; i++)
{
NSDate *myDate = [formatter1 dateFromString:[datesArray objectAtIndex:i]];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:myDate];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:myTime];
NSDateComponents * newComponents = [[NSDateComponents alloc]init];
NSDateComponents *todayComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
int day = [dateComponents day];
int month = [dateComponents month];
[newCompoents setDay:[dateComponents day]];
[newCompoents setMonth:[dateComponents month]];
if (day >= [todayComponents day] && month >= [todayComponents month]) {
NSLog(#"day = %d, month = %d", day, month);
[newComponents setYear:[todayComponents year]];
} else {
NSLog(#"%d, %d", day, month);
[newComponents setYear:[todayComponents year]+1];
}
[newComponents setHour:[timeComponents hour]];
[newComponents setMinute:[timeComponents minute]];
NSDate *combDate = [calendar dateFromComponents: newComponents];
localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = combDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
NSString *message = [#"Wish" stringByAppendingFormat:#" %#%#", [messagesArray objectAtIndex:i],#" On His Birthday"];
localNotif.alertBody = message;
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:notificationID forKey:notificationID];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
}
correct me if I am making any mistakes and suggest how to schedule more notifications once 64 limit is crossed.
I have a similar problem and a few additional options that may help you, though they all have flaws that means correct behavior is not guaranteed.
Keep in mind that overlapping birthdays could be useful here. If two people end up having a birthday on the same day, cancel and reschedule with both of their info associated. You could find other intervals where repetition occurs if you're OK w/ a generic message.
Obviously, encouring your user to press the notification to open the app would help (possible with your ad revenue too). You could try a nice message for your last one.
It's hacky, but you could use geofencing (but probably not remote notifications) as described here: Can push notifications be used to run code without notifying user? . If you add a feature that uses it, you might even be able to get it approved.
I've considered passing a custom calendar as well, but NSCalendar is toll free bridged to CFCalendarRef and the story seems to be that I'm not going to have luck trying to dig into that (and getting it approved at least). I would be happy to be told I'm wrong.

How to set an Alarm in iOS?

I know this question has asked many times on StackOverflow but i couldn't able to set alarm in my app because i am very new to iOS? I am following this tutorial to set an alarm:
Setting a reminder using UILocalNotification in iOS.
However, it doesn't seems to be working for me.
I am in need to set alarm daily lets say 5.00 PM daily. I can't use date picker for choosing the time.
First on your xib, (or code) set the date picker mode: Time (Default is date & time)
The system assumes that the firedate is the current date, and the time is the time the user have chosen. This is not a problem because you set a repeat interval so it will work. I have tested it.
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
[localNotif setFireDate:datePicker.date];
[localNotif setRepeatInterval:NSDayCalendarUnit];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
PS: It would be a good idea to set the seconds to 0 using NSDateComponents class so as to set the alarm to ring at the first second of the minute you want. You can check the:
Local notifications in iOS.
tutorial you posted on how to do this.
+ (void)addLocalNotification:(int)year:(int)month:(int)day:(int)hours:(int)minutes:(int)seconds:(NSString*)alertSoundName:(NSString*)alertBody:(NSString*)actionButtonTitle:(NSString*)notificationID
Call this method with parameters and use this
+ (void)addLocalNotification:(int)year:(int)month:(int)day:(int)hours:(int)minutes:(int)seconds:(NSString*)alertSoundName:(NSString*)alertBody:(NSString*)actionButtonTitle:(NSString*)notificationID {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
//set the notification date/time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:day];
[dateComps setMonth:month];
[dateComps setYear:year];
[dateComps setHour:hours];
[dateComps setMinute:minutes];
[dateComps setSecond:seconds];
NSDate *notificationDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = notificationDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Set notification message
localNotif.alertBody = alertBody;
// Title for the action button
localNotif.alertAction = actionButtonTitle;
localNotif.soundName = (alertSoundName == nil) ? UILocalNotificationDefaultSoundName : alertSoundName;
//use custom sound name or default one - look here to find out more: http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html%23//apple_ref/doc/uid/TP40008194-CH103-SW13
localNotif.applicationIconBadgeNumber += 1; //increases the icon badge number
// Custom data - we're using them to identify the notification. comes in handy, in case we want to delete a specific one later
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:notificationID forKey:notificationID];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
You may need to change the style of the date picker to allow changing the time in addition to just the date.
You can try this
UILocalNotification *todolistLocalNotification=[[UILocalNotification alloc]init];
[todolistLocalNotification setFireDate:[lodatepicker date]];
[todolistLocalNotification setAlertAction:#"Note list"];
[todolistLocalNotification setTimeZone:[NSTimeZone defaultTimeZone]];
[todolistLocalNotification setAlertBody:text_todolist];
[todolistLocalNotification setHasAction:YES];

Resources