My localNotification isn't working - iphone

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

Related

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;

Change UILocalNotification count at the panel

i have meet the problem: when i send a UILocalNotification as:
UILocalNotification *alarm = [[UILocalNotification alloc] init];
if (alarm) {
alarm.fireDate = [NSDate date];
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.soundName = UILocalNotificationDefaultSoundName;
alarm.alertBody ="This is 1 message";
if (object) {
NSDictionary *infoDic = [NSDictionary dictionaryWithObject:object forKey:objectkey];
alarm.userInfo = infoDic;
}
[[UIApplication sharedApplication] presentLocalNotificationNow:alarm];
you can see the code:when i send the notication twice you can receive the message twice:
"This is 1 message"
"This is 1 message"
at the panel of mobile. i want to not change the alarm.alertBody content,but when i receive the message twice,i can merge the two meaasge
"This is 1 message"
"This is 1 message" as one "there are two messages" on the panel . if i can finished the task,if yes,what api can i use?
in android status info and panel info is different,but i think iOS only one alert body,at status and panel is the same am i right?
Edit: i donot know why give me -2,my quetion is easy? or other? the answer not my need.
edit 2: i describe my need. when user receive different 1 message form 15 people,it come one by one,so i cannot give it [NSString stringWithFormat:#"there are %d messages",count],i only give it "there is 1 message",but when user open the panel,i only show" there are 15 message",can cannel 14 "there is 1 message". answer 1,give me answer is :at status "there is 15 message" ,but not people give me so many message,people only give me 1 message
You can create a function to schedule the notification.
Create an array for the alert msgs use counter +1 for adding new alert each time.
Then you can schedule the local notification on a particular date as you want some thing like this would help:
- (void)scheduleNotification:(NSDate*)showDate withMsg:(NSString*)msg
{
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
// notif.fireDate = [datePicker date];
//setting the fire dat of the local notification
notif.fireDate = showDate;//[NSDate dateWithTimeIntervalSinceNow:5];
//setting the time zone
notif.timeZone = [NSTimeZone defaultTimeZone];
//setting the message to display
//notif.alertBody = #"You are notified";
notif.alertBody = msg;
//default notification sound
notif.soundName = UILocalNotificationDefaultSoundName;
//displaying the badge number
notif.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
//schedule a notification at its specified time with the help of the app delegate
// NSLog(#"Todays date:%# Notification Date:%#",[NSDate date],showDate);
// Displaying Button tittle
notif.alertAction = #"Show me";
// //setting the values in dict of local notification
// NSDictionary *userDict = [NSDictionary dictionaryWithObject:_serverMsg
// forKey:kRemindMeNotificationDataKey];
// notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
}

Local Notification pop-up is displayed after killing the application

I have implemented Local notification in my application, I had a issue in below scenario:
Scenario:App is launched, Location notification will be created to display after a week from current date in login screen,I have logged in with credentials and after logging in double tap on the device's Home button (bottom center phisical key) to bring up the recently used applications bar then tap and hold on the application icon in order to be able to kill the application.After killing the application the notification pop-up is presented without waiting for a week time
Below is the code:
- (void)applicationWillTerminate:(UIApplication *)application
{
if (iPhoneClientConfig::getInstance()->getReminder() == RS_NONE) {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
else {
int daysToAdd;
NSString *alertText;
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
if (iPhoneClientConfig::getInstance()->getReminder() == RS_MONTH) {
daysToAdd = 60*60*24*30;
alertText = [Localization getLanguage:#"reminder_message_month"];
localNotification.repeatInterval = NSMonthCalendarUnit;
[self generateAlertNotifications:daysToAdd withtext:alertText ];
} else if (iPhoneClientConfig::getInstance()->getReminder() == RS_DAY) {
daysToAdd = 60*60*24;
alertText = [Localization getLanguage:#"reminder_message_day"];
localNotification.repeatInterval = NSDayCalendarUnit;
} else if (iPhoneClientConfig::getInstance()->getReminder() == RS_HOUR) {
daysToAdd = 60*60;
alertText = [Localization getLanguage:#"reminder_message_hour"];
localNotification.repeatInterval = NSHourCalendarUnit;
} else {
if (iPhoneClientConfig::getInstance()->getReminder() != RS_WEEK) {
LOG.error("%s: Unexpetected reminder repeat interval in configuration, fall back to week",__FUNCTION__);
}
daysToAdd = 60*60*24*7;
alertText = [Localization getLanguage:#"reminder_message_week"];
localNotification.repeatInterval = NSWeekCalendarUnit;
[self generateAlertNotifications:daysToAdd withtext:alertText];
}
NSDate *today = [NSDate date];
NSDate *newDate = [today addTimeInterval:daysToAdd];
NSLog(#"newDate:%#",newDate);
// Set up the fire time
localNotification.fireDate = newDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
// Notification details and Set the action button
localNotification.alertBody = alertText;
localNotification.alertAction = [Localization getLanguage:#"local_notif_alert"];
localNotification.soundName = UILocalNotificationDefaultSoundName;
//Schedule LocalNotification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
NSLog(#"local_notif_alert:%#",localNotification);
[localNotification release];
}
}
I have the fire date & local notification in console as below:
Date:2012-09-01 10:49:08 +0000
local_notif_alert:<UIConcreteLocalNotification: 0xd006d20>{fire date = Saturday, September 1, 2012 4:19:08 PM India Standard Time, time zone = Asia/Kolkata (IST) offset 19800, repeat interval = NSWeekCalendarUnit, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, September 1, 2012 4:19:08 PM India Standard Time}
Of course. Once they are scheduled, local notifications have a life of their own.
This is what you have to do: call
[[UIApplication sharedApplication] cancelAllLocalNotifications];
for example in applicationWillTerminate:.
As for the unexpected notification appearing too early: NSLog the notification details and make sure you got the scheduling right.

iPhone : Is it possible to get each different text in alert for local notification?

My app use to select different text data from the database. And we have functionality which display local notification every day.
I am using following code :
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"Hey"; // Can I select random message for this notification?
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
Now Is it possible to display different text data for local notification? How ?
you can create an array of string and every time choose a random object and assign it to localnotif body .

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;