iOS10 UNNotificationRequest set identifier is #"", device crash and restart constantly - ios10

My code like this :
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.badge = #1;
content.body = #"body";
content.sound = [UNNotificationSound defaultSound];
content.subtitle = #"subtitle";
content.title = #"title";
NSDateComponents *components = [NSDateComponents new];
components.year = 2016;
components.month = 10;
components.day = 26;
components.hour = 10;
components.minute = 35;
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:#"" content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {}];
I made a mistake,[UNNotificationRequest requestWithIdentifier:#"" content:content trigger:trigger];set identifier with #"", and run on my device.
And then my device crash and restart again and again.As in the above case, I try to run it on simulator, simulator restart again and again until I reset content and settings.
Now my device can't connect to computer, because it restart again and again and I can't unlock it. So I can't uninstall the error app and reset it. How can this problem be solved?

Related

My localNotification isn't working

i got following code which contains my localNotification:
-(void)scheduleNotification{
if (self.shouldRemind && [self.dueDate compare:[NSDate date]] != NSOrderedAscending){
UILocalNotification *localNotification = [UILocalNotification new];
localNotification.fireDate = self.dueDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = self.text;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:self.itemId] forKey:#"ItemId"];
NSLog(#"Scheduled notification %# for itemId %d", localNotification, self.itemId);
}
}
My output in NSLog says following:
2013-07-28 15:39:48.684 JuneChecklist[2271:907] Scheduled notification {fire date = воскресенье, 28 июля 2013 г., 15:40:33 Московское стандартное время, time zone = Europe/Moscow (GMT+04:00) offset 14400, repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = воскресенье, 28 июля 2013 г., 15:40:33 Московское стандартное время, user info = {
ItemId = 0;
}} for itemId 0
But it is not shown (i tried launch app on iPhone and Simulator). I wonder why it shown fireDate in NSLog perfectly, but there is no notification when i wait for that time.
Any advice would be appreciated.
But where is [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];?

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

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;

how to cancel a local notification in 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;
}
}
}
}