how to cancel a local notification in iphone - iphone

I am making the application that has needs to set the notification , thankfully i was able t set the local notification but i dont know how to delete the notification which is set by this application(my aplicaton ).The xcode does provide functionality of delete with removeAllNotifications but you cannot remove the selected notifications set by the application

You can call [[UIApplication sharedApplication] cancelLocalNotification:notification] to cancel a notification. Since local notifications conform to the NSCoding protocol, they can be stored and retrieved for later canceling.

I know this post is old but hope this solution helps someone
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for(UILocalNotification *notification in notificationArray){
if ([notification.alertBody isEqualToString:#"your alert body"] && (notification.fireDate == your alert date time)) {
// delete this notification
[[UIApplication sharedApplication] cancelLocalNotification:notification] ;
}
}
I am comparing the alert body and date time just to make sure that i am deleting the right notification since there are chances where two or more notifications can have the same alert body or time.

Local Notification in iOS 10 and Below iOS 10 with Xcode 8 beta 2
pragma mark - Calculate Before Date
-(void) calculateBeforedays:(int)_day hours:(int)_hours minutes:(int) _minutes { //_fir:(int)_firecount
//Get Predefined Future date
NSString *dateString = [NSString stringWithFormat:#"%#T%#:00.000Z",_eventdate,_eventtime];
NSLog(#"dateString %#",dateString);
// NSLog(#"_firecount %d",_firecount);
// //Get Predefined Future date
// NSString *dateString = [NSString stringWithFormat:#"2016-12-31T12:%d:00.000Z",_firecount];
// NSLog(#"dateString %#",dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate *marrigeDate = [dateFormatter dateFromString:dateString];
// Set reminder date before marrige date
int setDay = _day;
int setHours = _hours;
int setMins = _minutes;
float milliseconds = (setDay * 24 * 60 * 60 ) + (setHours * 60 * 60 ) + (setMins * 60 );
NSDate *someDateInUTC = [NSDate date];
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
//Get Current date
NSDate *currentDate = dateInLocalTimezone;
NSTimeInterval marigeTimeInterval = [marrigeDate timeIntervalSinceDate:currentDate];
//Get difference between time
NSTimeInterval timeIntervalCountDown = marigeTimeInterval - milliseconds;
//Set perticulater timer
NSDate *timerDate = [NSDate dateWithTimeIntervalSinceNow:timeIntervalCountDown];
[self triggerNotification:timerDate];
}
#pragma mark- Trigger Reminders
- (void)triggerNotification:(NSDate *) reminderDate {
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
// create actions
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// create actions
UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:#"com.inviteapp.yes"
title:#"Accept"
options:UNNotificationActionOptionForeground];
UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:#"com.inviteapp.no"
title:#"Decline"
options:UNNotificationActionOptionDestructive];
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"com.inviteapp.snooze"
title:#"Snooze"
options:UNNotificationActionOptionDestructive];
NSArray *notificationActions = #[ acceptAction, declineAction, snoozeAction ];
// create a category
UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier actions:notificationActions intentIdentifiers:#[] options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:inviteCategory];
// registration
[center setNotificationCategories:categories];
#endif
}
else if([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0f){
// create actions
UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = #"com.inviteapp.yes";
acceptAction.title = #"Accept";
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO; //If YES requies passcode, but does not unlock the device
UIMutableUserNotificationAction *declineAction = [[UIMutableUserNotificationAction alloc] init];
declineAction.identifier = #"com.inviteapp.no";
acceptAction.title = #"Decline";
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
declineAction.destructive = YES;
acceptAction.authenticationRequired = NO;
UIMutableUserNotificationAction *snoozeAction = [[UIMutableUserNotificationAction alloc] init];
snoozeAction.identifier = #"com.inviteapp.snooze";
acceptAction.title = #"Snooze";
snoozeAction.activationMode = UIUserNotificationActivationModeBackground;
snoozeAction.destructive = YES;
snoozeAction.authenticationRequired = NO;
// create a category
UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = CYLInviteCategoryIdentifier;
NSArray *notificationActions = #[ acceptAction, declineAction, snoozeAction ];
[inviteCategory setActions:notificationActions forContext:UIUserNotificationActionContextDefault];
[inviteCategory setActions:notificationActions forContext:UIUserNotificationActionContextMinimal];
// registration
NSSet *categories = [NSSet setWithObject:inviteCategory];
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
/// 2. request authorization for localNotification
[self registerNotificationSettingsCompletionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(#"request authorization succeeded!");
}
}];
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
[self localNotificationForiOS10:reminderDate];
#endif
} else {
[self localNotificationBelowiOS10: reminderDate];
}
}
- (void)registerNotificationSettingsCompletionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler; {
/// 2. request authorization for localNotification
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:completionHandler];
#endif
} else if([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0f){
UIUserNotificationSettings *userNotificationSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge)
categories:nil];
UIApplication *application = [UIApplication sharedApplication];
[application registerUserNotificationSettings:userNotificationSettings];
}
}
for setting multiple notifications:
iOS 10, add different requestWithIdentifier
pragma mark- Locanotification more than iOS 10
-(void) localNotificationForiOS10:(NSDate *) _reminderDate{
_eventReminderDate = _reminderDate;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:_reminderDate];
NSLog(#"NSDateComponents %#",components);
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:_eventname arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:#"You have event reminder"
arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
/// 4. update application icon badge number
objNotificationContent.badge = #([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:#"eventdate"
content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(#"Local Notification succeeded");
}
else {
NSLog(#"Local Notification failed");
}
}];
}
for setting multiple notifications below iOS 10, add different userinfo
pragma mark- Locanotification less than iOS 10
-(void) localNotificationBelowiOS10:(NSDate *) _reminderDate{
_eventReminderDate = _reminderDate;
NSLog(#"dateInLocalTimezone %#",_eventReminderDate);
/// 3. schedule localNotification
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = _eventReminderDate ;
localNotification.alertTitle = _eventname;
localNotification.alertBody = #"You have Event Name";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = 0;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSDictionary *info = [NSDictionary dictionaryWithObject:_eventname forKey:_eventname];
localNotification.userInfo = info;
NSLog(#"info ---- %#",info);
NSLog(#"notification userInfo gets name : %#",[info objectForKey:_eventname]);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
pragma mark- Delete Perticulater Local Notification
-(IBAction)deleteReminder:(id)sender{
UIButton *senderButton = (UIButton *)sender;
_selectedRow = senderButton.tag;
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:senderButton.tag inSection:0]; // if section is 0
ReminderCell * cell = (ReminderCell*)[_tableView cellForRowAtIndexPath:indexPath];
_eventname = [[_eventArray objectAtIndex:indexPath.row] objectForKey:#"event_name"];
_eventdate = [[_eventArray objectAtIndex:indexPath.row] objectForKey:#"event_date"];
_eventtime = [[_eventArray objectAtIndex:indexPath.row] objectForKey:#"event_st"];
if([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f){
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// remove all local notification:
[center removePendingNotificationRequestsWithIdentifiers:#[_eventname]];
#endif
} else {
NSLog(#"Delete notification below ios 10");
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 *ename=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:_eventname]];
if ([ename isEqualToString:_eventname])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
}

Related

UILocalNotification is not getting cancelled

I am trying to cancel a already scheduled notification , notification is getting called but when i try to cancel a notification its not getting cancelled .
NSArray notification contains some random values when there is only one scheduled notification. can anyone help me . I am want to cancel the notification for a particular bookID.
UPDATE :
-(UILocalNotification *)scheduleNotification :(int)remedyID
{
NSString *descriptionBody;
NSInteger frequency;
UILocalNotification *notif = [[UILocalNotification alloc] init];
NSLog(#"%d",remedyID);
descriptionBody =[[self remedyDetailsForRemedyID:remedyID] objectForKey:#"RemedyTxtDic"];
frequency = [[[self remedyDetailsForRemedyID:remedyID] objectForKey:#"RemedyFrequency"]intValue];
NSArray *notificationFireDates = [self fireDatesForFrequency:frequency];
for (NSDate *fireDate in notificationFireDates)
{
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = NSDayCalendarUnit;
notif.alertBody = [NSString stringWithString:descriptionBody];
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
notif.fireDate = fireDate;
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:notif.alertBody, #"kRemindMeNotificationDataKey", [NSNumber numberWithInt:remedyID],kRemindMeNotificationRemedyIDKey,
nil];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
return notif;
}
- (void)cancelNotification:(int)bookID
{
int notificationBook=0;
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (UILocalNotification *notification in notifications)
{
int notifBookId = [[notification.userInfo objectForKey:kRemindMeNotificationBookIDKey] intValue];
for (int i=0; i<[bookArray count]; i++)
{
notificationBook =[[[remedyArray objectAtIndex:i] objectForKey:#"BookID"] intValue];
}
NSLog(#"%d",[[notification.userInfo objectForKey:kRemindMeNotificationBookIDKey]intValue]);
NSLog(#"%d",notifBookId);
if (bookId == notifBookId)
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
}
NSArray notification contains some random values when there is only one scheduled notification.
It may be due to some previously scheduled notifications of that application already exists. Once try to cancel all the notifications of app starts again
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Your main problem
- (void)cancelNotification:(int)remedyId
{
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
NSLog(#"Cancelling... Before %d",[[[UIApplication sharedApplication]scheduledLocalNotifications]count]);
for (UILocalNotification *notification in notifications)
{
int notifRemedyId = [[notification.userInfo objectForKey:#"kRemindMeNotificationRemedyIDKey"]intValue]; // I change the key value
NSLog(#"remedyID : %d",remedyId);
NSLog(#"notifyId : %d",notifRemedyId);
if (remedyId == notifRemedyId) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
NSLog(#"Cancelling... After %d",[[[UIApplication sharedApplication]scheduledLocalNotifications]count]);
}
The key you have given was wrong. I think that was your problem. I figured out one more thing you are scheduling each notification twice i dont know why. Check with that.
You should move the check the inside the loop
for (int i=0; i<[bookArray count]; i++)
{
int bookId =[[[remedyArray objectAtIndex:i] objectForKey:#"BookID"] intValue];
if (bookId == notifBookId)
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}

How can we set repeatinterval for UIlocalNotifications biweekly (twice in a month)? [duplicate]

I am making an iPhone app, which has a requirement of Local Notifications.
In local notifications there is repeatInterval property where we can put the unit repeat intervals for mintute, hour, day,week,year, etc.
I want that repeat interval should be 4 hours.
So every 4 hours the local notification comes.
I dont want the user to set seperate notifications for each.
I want the user to be able to set repeatInterval as 4 hours.
How do I do that?
Got the answer, it is as straight as it gets.
You cannot create custom repeat intervals.
You have to use on NSCalendarUnit's in-built Unit Time Intervals.
I tried all the above solutions and even tried other stuffs, but neither of them worked.
I have invested ample time in finding out that there is no way we can get it to work for custom time intervals.
The repeat interval is just an enum that has a bit-map constant, so there is no way to have custom repeatIntervals, just every minute, every second, every week, etc.
That being said, there is no reason your user should have to set each one. If you let them set two values in your user interface, something like "Frequency unit: Yearly/Monthly/Weekly/Hourly" and "Every ____ years/months/weeks/hours" then you can automatically generate the appropriate notifications by setting the appropriate fire date without a repeat.
UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSInterval interval;
switch( freqFlag ) { // Where freqFlag is NSHourCalendarUnit for example
case NSHourCalendarUnit:
interval = 60 * 60; // One hour in seconds
break;
case NSDayCalendarUnit:
interval = 24 * 60 * 60; // One day in seconds
break;
}
if( every == 1 ) {
locNot.fireDate = [NSDate dateWithTimeInterval: interval fromDate: now];
locNot.repeatInterval = freqFlag;
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
} else {
for( int i = 1; i <= repeatCountDesired; ++i ) {
locNot.fireDate = [NSDate dateWithTimeInterval: interval*i fromDate: now];
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
}
}
[locNot release];
I have one idea how to do this, i've implemented this in my project
First, create local notification with fire date (for example, every minute).
Next step - fill user info with unique id for this notification (if you want to remove it in future) and your custom period like this:
-(void) createLocalRepeatedNotificationWithId: (NSString*) Id
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSTimeInterval your_custom_fire_interval = 60; // interval in seconds
NSDate *remindDate = [[NSDate date] dateByAddingTimeInterval:your_custom_fire_interval];
localNotification.fireDate = remindDate;
localNotification.userInfo = #{#"uid":Id, #"period": [NSNumber numberWithInteger:your_custom_fire_interval]};
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
After that, implement -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification in your AppDelegate:
Fetch your custom period from user info.
Change fire date for next period
Just add it into the sheluded notificatiots again!
NSInteger period = [[notification.userInfo objectForKey:#"period"] integerValue]; //1
NSTimeInterval t= 10 * period;
notification.fireDate =[[NSDate date] dateByAddingTimeInterval:t]; //2
[[UIApplication sharedApplication] scheduleLocalNotification:notification]; //3
if you want to remove this notification, do
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 *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"id"]];
if ([uid isEqualToString:notification_id_to_remove])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
Very important!
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification do not called, when you at background. So, you must setup long-running background task, where you will create notification again.
i have used this code and it is working fine for repeat LocalNotification i have used LavaSlider Code for this code implemetation
UILocalNotification * localNotifEndCycle = [[UILocalNotification alloc] init];
localNotifEndCycle.alertBody = #"Your Expected Date ";
NSDate *now = [NSDate date];
for( int i = 1; i <= 10;i++)
{
localNotifEndCycle.alertBody = #"Your Expected Date ";
localNotifEndCycle.soundName=#"best_guitar_tone.mp3";
localNotifEndCycle.fireDate = [NSDate dateWithTimeInterval:180*i sinceDate:now];
[[UIApplication sharedApplication] scheduleLocalNotification: localNotifEndCycle];
}
}
-(void)schedulenotificationfortimeinterval:(NSString *)id1
{
NSLog(#"selected value %d",selectedvalue);
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MMM dd,yyyy hh:mm a"];
UILocalNotification *localNotification2 = [[UILocalNotification alloc] init];
// localNotification2. fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:0];
if(selectedvalue==0)
{
NSLog(#"dk 0000");
localNotification2.fireDate = [formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] ;//now
localNotification2.applicationIconBadgeNumber = 1;
localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==1)
{
NSLog(#"dk 1111");
for( int u = 0; u <= 2 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:43200.0*u] ;// 12 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 2;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==2)
{
NSLog(#"dk 22222");
for( int u = 0; u <= 3 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:28800.0*u] ;//8 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 3;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==3)
{
NSLog(#"dk 3333");
for( int u = 0; u <= 4 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:21600.0*u] ;//6 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 4;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
NSLog(#"date is %# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]);
localNotification2.timeZone = [NSTimeZone localTimeZone];
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
//localNotification2.applicationIconBadgeNumber = 1;
// infoDict = [NSDictionary dictionaryWithObject:id1 forKey:#"did"];
// localNotification2.userInfo = infoDict;
// [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
// NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
// [[UIApplication sharedApplication] cancelAllLocalNotifications];//dk
}
You can set any time interval you want, if you set up separate notifications for each time you want a notification to fire. You then have to manage them, and if you are not an app that is at present allowed to run in the background, you'll have to refresh them by having the user run your app to do so. Having accomplished this, I can tell you it is a major PITA.
//This is how I set local notification based on time interval repeatedly and executed method customized snooze and delete
let content = UNMutableNotificationContent()
content.title = "Time Based Local Notification"
content.subtitle = "Its is a demo"
content.sound = .default
content.categoryIdentifier = "UYLReminderCategory"
//repition of time base local notification in foreground, background, killed
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "IOS Demo", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "UYLDeleteAction", title: "Delete", options: [.destructive])
let cat = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction,deleteAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([cat])
notif.repeatInterval = NSDayCalendarUnit;

how i use iPhone calendar add event?

I want use iPhone calendar add Event.
I try ti.com.calendar module from github but in this module only save startTime EndTime, Title and details.
but, not use allDay repeat or not reminder.
How i use this. in calendar?
I also user notification for reminder. but, after delete event. the notification is not delete.
any suggestion is appreciated
bellow is peace of code. date for alarm is using to match work hours (users don't like to wakeup to do job :)
eventStore = [[EKEventStore alloc] init];
EKEvent *newEvent = [EKEvent eventWithEventStore:eventStore];
newEvent.calendar = eventStore.defaultCalendarForNewEvents;
NSString *titleForEvent = [NSString stringWithFormat:#"In country:%# will be:\n%# event",[mo valueForKey:#"name"],[mo valueForKey:#"necessaryData"]];
newEvent.title = titleForEvent;
newEvent.allDay = YES;
NSDate *date = [mo valueForKey:#"date"];
NSDate *dateAlarm = [mo valueForKey:#"dateAlarm"];
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:[dateAlarm timeIntervalSinceDate:date]];
if (dateAlarm < [NSDate date]){
dateAlarm = [NSDate dateWithTimeIntervalSinceNow:+18000];
NSDateFormatter *dateForm = [[NSDateFormatter alloc]init];
[dateForm setDateFormat:#"%HH"];
NSString *hourOfAlarm = [dateForm stringFromDate:dateAlarm];
[dateForm release];
NSNumberFormatter *numberForm = [[NSNumberFormatter alloc] init];
NSNumber *hour = [numberForm numberFromString:hourOfAlarm];
[numberForm release];
int difference = 0;
if ([hour intValue] < 9) difference = (9 - [hour intValue]) *3600;
if ([hour intValue] > 17) difference = (17 - [hour intValue]) *3600;
if (difference != 0) {
NSTimeInterval interval = 18000 + difference;
dateAlarm = [NSDate dateWithTimeIntervalSinceNow:interval];
}
alarm = [EKAlarm alarmWithRelativeOffset:[dateAlarm timeIntervalSinceDate:date]];
}
newEvent.startDate = date;
newEvent.endDate = date;
//EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:[dateAlarm timeIntervalSinceDate:date]];
newEvent.alarms = [NSArray arrayWithObject:alarm];
NSError *error;
BOOL saved = [eventStore saveEvent:newEvent span:EKSpanThisEvent error:&error];
if (!saved && error) {
NSLog(#"%#",[error localizedDescription]);
} else [mo setValue:newEvent.eventIdentifier forKey:#"eventIdentifier"];

Help with local notifications!

I tried a verity of blogs but from some reason it doesn't fire!
Can it be because I don't ask permission? Am I suppose to ask the user for local? I understand from apple's documentation that I don't.
This is my singelton class (Checked it is called - with a breakpoint)
//
// «FILENAME»
// «PROJECTNAME»
//
// Created by «FULLUSERNAME» on «DATE».
// Copyright «YEAR» «ORGANIZATIONNAME». All rights reserved.
// File created using Singleton XCode Template by Mugunth Kumar (http://mugunthkumar.com
// Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
#import "NotifierSingelton.h"
static NotifierSingelton* _instance;
#implementation NotifierSingelton
+ (NotifierSingelton*)sharedInstance
{
#synchronized(self) {
if (_instance == nil) {
// iOS 4 compatibility check
Class notificationClass = NSClassFromString(#"UILocalNotification");
if(notificationClass == nil)
{
_instance = nil;
}
else
{
_instance = [[super allocWithZone:NULL] init];
}
// Allocate/initialize any member variables of the singleton class her
// example
//_instance.member = #"";
}
}
return _instance;
}
- (void) scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
localNotification.alertLaunchImage = launchImage;
//self.badgeCount ++;
localNotification.applicationIconBadgeNumber = 1;
localNotification.userInfo = userInfo;
// Schedule it with the app
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
}
#pragma mark Singleton Methods
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance]retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
#end
I don't really see anything wrong with your code. Make sure your firedate is not null. Here is working code form one of my apps:
notif = [[UILocalNotification alloc] init];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *raceDate = [df dateFromString:[raceDates objectAtIndex:i]];
notif.fireDate = raceDate;
notif.timeZone = [NSTimeZone timeZoneWithName:#"WAT"];
notif.alertBody = NSLocalizedString(#"NotificationBody", #"");
notif.alertAction = NSLocalizedString(#"NotificationButton", #"");
notif.soundName = #"push.aif";
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
Also, I'm not sure if it's required but your app may need to be multi-tasking enabled.

How to set Local Notification repeat interval to custom time interval?

I am making an iPhone app, which has a requirement of Local Notifications.
In local notifications there is repeatInterval property where we can put the unit repeat intervals for mintute, hour, day,week,year, etc.
I want that repeat interval should be 4 hours.
So every 4 hours the local notification comes.
I dont want the user to set seperate notifications for each.
I want the user to be able to set repeatInterval as 4 hours.
How do I do that?
Got the answer, it is as straight as it gets.
You cannot create custom repeat intervals.
You have to use on NSCalendarUnit's in-built Unit Time Intervals.
I tried all the above solutions and even tried other stuffs, but neither of them worked.
I have invested ample time in finding out that there is no way we can get it to work for custom time intervals.
The repeat interval is just an enum that has a bit-map constant, so there is no way to have custom repeatIntervals, just every minute, every second, every week, etc.
That being said, there is no reason your user should have to set each one. If you let them set two values in your user interface, something like "Frequency unit: Yearly/Monthly/Weekly/Hourly" and "Every ____ years/months/weeks/hours" then you can automatically generate the appropriate notifications by setting the appropriate fire date without a repeat.
UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSInterval interval;
switch( freqFlag ) { // Where freqFlag is NSHourCalendarUnit for example
case NSHourCalendarUnit:
interval = 60 * 60; // One hour in seconds
break;
case NSDayCalendarUnit:
interval = 24 * 60 * 60; // One day in seconds
break;
}
if( every == 1 ) {
locNot.fireDate = [NSDate dateWithTimeInterval: interval fromDate: now];
locNot.repeatInterval = freqFlag;
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
} else {
for( int i = 1; i <= repeatCountDesired; ++i ) {
locNot.fireDate = [NSDate dateWithTimeInterval: interval*i fromDate: now];
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
}
}
[locNot release];
I have one idea how to do this, i've implemented this in my project
First, create local notification with fire date (for example, every minute).
Next step - fill user info with unique id for this notification (if you want to remove it in future) and your custom period like this:
-(void) createLocalRepeatedNotificationWithId: (NSString*) Id
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSTimeInterval your_custom_fire_interval = 60; // interval in seconds
NSDate *remindDate = [[NSDate date] dateByAddingTimeInterval:your_custom_fire_interval];
localNotification.fireDate = remindDate;
localNotification.userInfo = #{#"uid":Id, #"period": [NSNumber numberWithInteger:your_custom_fire_interval]};
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
After that, implement -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification in your AppDelegate:
Fetch your custom period from user info.
Change fire date for next period
Just add it into the sheluded notificatiots again!
NSInteger period = [[notification.userInfo objectForKey:#"period"] integerValue]; //1
NSTimeInterval t= 10 * period;
notification.fireDate =[[NSDate date] dateByAddingTimeInterval:t]; //2
[[UIApplication sharedApplication] scheduleLocalNotification:notification]; //3
if you want to remove this notification, do
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 *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"id"]];
if ([uid isEqualToString:notification_id_to_remove])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
Very important!
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification do not called, when you at background. So, you must setup long-running background task, where you will create notification again.
i have used this code and it is working fine for repeat LocalNotification i have used LavaSlider Code for this code implemetation
UILocalNotification * localNotifEndCycle = [[UILocalNotification alloc] init];
localNotifEndCycle.alertBody = #"Your Expected Date ";
NSDate *now = [NSDate date];
for( int i = 1; i <= 10;i++)
{
localNotifEndCycle.alertBody = #"Your Expected Date ";
localNotifEndCycle.soundName=#"best_guitar_tone.mp3";
localNotifEndCycle.fireDate = [NSDate dateWithTimeInterval:180*i sinceDate:now];
[[UIApplication sharedApplication] scheduleLocalNotification: localNotifEndCycle];
}
}
-(void)schedulenotificationfortimeinterval:(NSString *)id1
{
NSLog(#"selected value %d",selectedvalue);
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MMM dd,yyyy hh:mm a"];
UILocalNotification *localNotification2 = [[UILocalNotification alloc] init];
// localNotification2. fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:0];
if(selectedvalue==0)
{
NSLog(#"dk 0000");
localNotification2.fireDate = [formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] ;//now
localNotification2.applicationIconBadgeNumber = 1;
localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==1)
{
NSLog(#"dk 1111");
for( int u = 0; u <= 2 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:43200.0*u] ;// 12 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 2;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==2)
{
NSLog(#"dk 22222");
for( int u = 0; u <= 3 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:28800.0*u] ;//8 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 3;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
if(selectedvalue==3)
{
NSLog(#"dk 3333");
for( int u = 0; u <= 4 ;u++)
{
localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:#"%# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]]] dateByAddingTimeInterval:21600.0*u] ;//6 hr
localNotification2.repeatInterval=NSDayCalendarUnit;
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
localNotification2.applicationIconBadgeNumber = 4;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
}
// localNotification2.repeatInterval=NSDayCalendarUnit;
NSLog(#"date is %# %#",[MedicationDict valueForKey:#"Starting"],[MedicationDict valueForKey:#"Ending"]);
localNotification2.timeZone = [NSTimeZone localTimeZone];
localNotification2.alertBody = [NSString stringWithFormat:#"Friendly reminder to take %# %# at %#.",[MedicationDict objectForKey:#"DrugName"],[MedicationDict objectForKey:#"Frequency"],[MedicationDict objectForKey:#"Ending"]];
localNotification2.alertAction = #"Notification";
localNotification2.soundName=UILocalNotificationDefaultSoundName;
//localNotification2.applicationIconBadgeNumber = 1;
// infoDict = [NSDictionary dictionaryWithObject:id1 forKey:#"did"];
// localNotification2.userInfo = infoDict;
// [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];
// NSLog(#"all notifications %#",[[UIApplication sharedApplication]scheduledLocalNotifications]);
// [[UIApplication sharedApplication] cancelAllLocalNotifications];//dk
}
You can set any time interval you want, if you set up separate notifications for each time you want a notification to fire. You then have to manage them, and if you are not an app that is at present allowed to run in the background, you'll have to refresh them by having the user run your app to do so. Having accomplished this, I can tell you it is a major PITA.
//This is how I set local notification based on time interval repeatedly and executed method customized snooze and delete
let content = UNMutableNotificationContent()
content.title = "Time Based Local Notification"
content.subtitle = "Its is a demo"
content.sound = .default
content.categoryIdentifier = "UYLReminderCategory"
//repition of time base local notification in foreground, background, killed
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "IOS Demo", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "UYLDeleteAction", title: "Delete", options: [.destructive])
let cat = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction,deleteAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([cat])
notif.repeatInterval = NSDayCalendarUnit;