I've been trying now for way too many hours without finding the problem/solution. this code is supposed to schedule a notification x days from now by comparing wd(the selected weekday) and item.itemDayName(Int of the current weekday). Right now the code only works when wd == 7, as wd == 7 --> all weekdays are selected (wd 0-6 = sun-sat). I will appreciate any feedback given, thank you.
- (void)scheduleNotificationWithItem:(ToDoItem *)item andWeekday:(int)wd{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
if (wd < 7) {
[dateComps setYear:item.itemYear];
[dateComps setMonth:item.itemMonth];
if (item.itemDayName != (wd + 1)) {
int result = (wd + 1) - item.itemDayName;
result = result + item.itemDay;
[dateComps setDay:result];
}
else{
[dateComps setDay:item.itemDay];
}
}
else {
[dateComps setYear:item.itemYear];
[dateComps setMonth:item.itemMonth];
[dateComps setDay:item.itemDay];
}
[dateComps setHour:item.itemHour];
[dateComps setMinute:item.itemMinute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
//localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(1*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
if (wd < 7) {
[localNotif setRepeatInterval: NSCalendarUnitWeekOfMonth];
}
else {
[localNotif setRepeatInterval: NSCalendarUnitDay]; //Repeat daily
}
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"Time to take %#!", nil),
item.itemName];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.alertTitle = NSLocalizedString(#"Piller", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.itemName forKey:item.itemKeyName];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
Related
Actually This question has been asked so many Times. But I have Confusion Among those. I have tried this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
Where cell is object of UITableviewCell, But There is Not any Type of Notification. I know there is a little Bug , please help me to find out.
Place the last line as [[UIApplication sharedApplication] scheduleLocalNotification:reminderNote]; after reminderNote.fireDate line.
log the reminderNote.fireDate and check the format.
Hope this helps.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
}
You can add the local notifications upto 64 at single time.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSDate *newDate = [fireDate dateByAddingTimeInterval:(6*60*60)];
// 6*60*60=6 hour*60 minutes*60 seconds
// [fireDate dateByAddingTimeInterval:(6*60*60*i)];
localNotification.fireDate = newDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = 0;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
localNotification.alertLaunchImage = launchImage;
localNotification.applicationIconBadgeNumber = 1;
localNotification.userInfo = userInfo;
// NSLog(#"%#", [localNotification description]);
// Schedule it with the app
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
If you want to keep all the objects of NSNotification, then you need to store that somewhere. i.e in Array.
You can also use following methods for NSNotifications operation.
- (void)cancelLocalNotification:(UILocalNotification *)notification
- (void)cancelAllLocalNotifications
Make sure you are receiving notifications on
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
As a good practice prior to use the object, make sure you have initialized and set all the values to particular object.
please try this for local notification
-(void)localnotification{
NSDate *pickerDate = [self.datepicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.labelname.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
Everything works fine with the following code if it is not change the day. But when change the day puts the badge 2 instead to put 1.
You know why this happens?
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = startDate;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [NSString stringWithFormat:#"%# '%#'.", NSLocalizedString (#"Tiene tareas pendientes para realizar en su acuario", ""), descripcionAcuario];
localNotification.alertAction = descripcionTextField.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSDictionary *inventory = #{
#"AcuarioID" : [NSNumber numberWithInt: acuarioSeleccionadoID],
#"TareaID" : [NSNumber numberWithInt: tareaSeleccionada],
};
localNotification.userInfo= inventory;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *alarmTimeStr = [[NSString alloc]init];
alarmTimeStr = [NSString stringWithFormat:#"%#",alarmTimeTextField.text];
NSDate *pickerdate = dateTimePicker.date;
[[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
startDate:&pickerdate
interval:NULL
forDate:pickerdate];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
pickerDate1 = pickerdate;
finaldate =pickerDate1;
// ** Local notification Assignment **
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = pickerDate1;
localNotification.alertBody = alarmNameTextField.text;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self setalarm];
-(void)setalarm
{
if ([sunValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:1];
[self setweek];
}
if ([monValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:2];
[self setweek];
}
if ([tueValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:3];
[self setweek];
}
if ([wedValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:4];
[self setweek];
}
if ([thuValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:5];
[self setweek];
}
if ([friValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:6];
[self setweek];
}
if ([satValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:7];
[self setweek];
}
alarmArray = [[DBManager sharedDatabase] getAlarmsDetail];
if ([alarmArray count] != 0)
{
[self showAllAlarmsInAlarmView];
}
if ([alarmArray count]==0)
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
}
-(void)setweek
{
#try
{
NSDateFormatter *formatterdate=[[NSDateFormatter alloc]init];
[formatterdate setDateFormat:#"YYYY-MM-dd"];
NSDateFormatter *formattertime =[[NSDateFormatter alloc]init];
[formattertime setDateFormat:#"HH:mm:ss"];
NSString * stringdate = [NSString stringWithFormat:#"%#",resultDate];
NSString *stringdate123 =[stringdate substringToIndex:10];
NSString *stringtime =[dateFormatter stringFromDate:pickerDate1];
NSString * stringtime123 =[stringtime substringFromIndex:11];
NSString * stringdate1234=[stringdate123 stringByAppendingString:#" "];
NSString * stringdate12345=[stringdate1234 stringByAppendingString:stringtime123];
finaldate =[dateFormatter dateFromString:stringdate12345];
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = finaldate;
localNotification.alertBody = alarmNameTextField.text;
localNotification.repeatInterval =NSWeekCalendarUnit;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];//#"Jai Hanuman.mp3";
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
#catch (NSException *exception)
{
[[saveClass shared_class] writeStringToFile:#"alarmViewController" andfunctionname:#"saveAlarmAndSetNotification" andexception:(NSString*)exception];
}
#finally
{}
}
-(NSDate *) getDateOfSpecificDay:(NSInteger ) day /// here day will be 1 or 2.. or 7
{
NSInteger desiredWeekday = day;
NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:finaldate];
NSLog(#"%#",[NSDate date]);
NSInteger currentWeekday = dateComponents.weekday;
if (desiredWeekday == currentWeekday)
{
differenceDays = 7;
daysComponents = [[NSDateComponents alloc] init];
}
else
{
differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
daysComponents = [[NSDateComponents alloc] init];
}
daysComponents.day = differenceDays;
resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:finaldate options:0];
return resultDate;
}
I am using the below code to display the notification at a fixed time. However it just does not fit my output.
- (IBAction)bt_set:(id)sender {
// Setting all the information about our date
int hour = 8;
int minutes = 19;
int day = 19;
int month = 10;
int year = 2014;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
[components setMinute:minutes];
[components setHour:hour];
NSDate *myNewDate = [calendar dateFromComponents:components];
//[components release];
//[calendar release];
[self scheduleNotificationForDate:myNewDate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Note"
message:#"Alarm has been set"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
This is the notfication code
- (void)scheduleNotificationForDate:(NSDate *)date
{
// Here we cancel all previously scheduled notifications
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
NSLog(#"%#",date);
NSLog(#"Notification will be shown on: %#",localNotification.fireDate);
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = [NSString stringWithFormat:#"Your notification message"];
localNotification.alertAction = NSLocalizedString(#"View details", nil);
/* Here we set notification sound and badge on the app's icon "-1"
means that number indicator on the badge will be decreased by one
- so there will be no badge on the icon */
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
This is the date I get in the log
Notification will be shown on: 2014-10-19 02:49:00 +0000
I guess it has something to do with the time zone.
I have the time zone of GMT+5:30
Please help me out
You have some (NSDate *)date----
Add below code to get the appropriate system time:
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
I am trying to schedule many UILocalNotifications at the same time. I refresh a lot of data and need to cancel all previous notifications and recreate them. Currently I have this code to cancel and create the notifications:
- (void)scheduleNotifications {
NSDate *start = [NSDate date];
// Cancel old notifications
[NotificationHandler cancelNotificationsNamed:#"ScheduleNotification"];
if (self.user.scheduleNotifications.boolValue) {
for (NSInteger i = 0; i < self.user.scheduleDays.count; i++) {
ScheduleDay *day = [self.user.scheduleDays objectAtIndex:i];
for (SchedulePeriod *period in day.periods) {
if (period.desc.length > 0) {
NSDateComponents *dateComponents = [[NSCalendar autoupdatingCurrentCalendar] components:NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:[NSDate date]];
dateComponents.day += 2 + i - dateComponents.weekday;
NSArray *timeComponents = [period.startTime componentsSeparatedByString:#":"];
NSInteger hour = [[timeComponents objectAtIndex:0] integerValue];
dateComponents.hour = hour < 7 ? hour + 12 : hour; // add 12 to hour if before 7 (assume afternoon)
dateComponents.minute = [[timeComponents objectAtIndex:1] integerValue] - 5;
NSDate *fireDate = [[NSCalendar autoupdatingCurrentCalendar] dateFromComponents:dateComponents];
if ([[NSDate date] compare:fireDate] == NSOrderedDescending) {
fireDate = [fireDate dateByAddingTimeInterval:604800]; // add a week if date is passed
}
[NotificationHandler scheduleNotificationNamed:#"ScheduleNotification"
forDate:fireDate
message:period.desc
repeatWeekly:YES];
}
}
}
}
NSLog(#"%f sec", [[NSDate date] timeIntervalSinceDate:start]);
}
NotificationHandler.m:
+ (void)scheduleNotificationNamed:(NSString *)name forDate:(NSDate *)date message:(NSString *)message repeatWeekly:(BOOL)repeatWeekly {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.userInfo = #{#"kNotificationName" : name};
notification.fireDate = date;
notification.alertBody = message;
notification.timeZone = [NSTimeZone defaultTimeZone];
if (repeatWeekly) {
notification.repeatInterval = NSCalendarUnitWeekOfYear;
}
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
+ (void)cancelNotificationsNamed:(NSString *)name {
for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[[notification userInfo] objectForKey:#"kNotificationName"] isEqualToString:name]) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
}
Unfortunately it can sometimes take a few seconds to cancel and create the notifications which blocks the UI. Is there a better way?
This is my localNotification codes.
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:13];
[components setMinute:11];
[components setDay: sonOdemeGunuNumber.integerValue -3];
NSDate *test = [calendar dateFromComponents:components];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = test;
localNotification.alertBody = [NSString stringWithFormat:#"%# 3 days left.",_txtBankaAdi.text];
localNotification.alertAction = #"Show item";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
localNotification.repeatInterval = kCFCalendarUnitDay;
localNotification.repeatInterval = kCFCalendarUnitMonth;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
sonOdemeGunuNumber is ToDoItem alert day(number of current day for example -3).
if(sonOdemeGunuNumber.integerValue == currentDay.integerValue){
localNotification.repeatInterval = nil; }
I wanted to notify user 3 days earlier and it should continue get alert until currentDay = sonOdemeGunuNumber.
1- If I write this if-else statement it will work ?
2- If user delete the localNotification Item in my TableView, in this case item is Bank Account ?
Bank Account localNotification will delete itself automatically ?
Thank you !
Have a nice day everyone...
I found the solution for if user delete the item in tableview i cancel deleted item's localNotification..
First of all, send ID with userInfo to the LocalNotification Center.
localNotification.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:_txtItemName.text,#"delThisNot", nil];
Secondly go and edit your tableView method.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
NSString *adi = [[self.fetchedResultsController objectAtIndexPath:indexPath]valueForKey:#"odemeAdi"];
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"delThisNot"]];
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
adi = Deleting item.
uid = your item id (which is your txtItemName.text)
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
if user want to delete item name (adi) == uid (txtItemName.Text)
Cancel this notification.
Sorry for my grammers I just wanted to help other people I hope you guys can understand me :D
Thanks.