I am using this code to add an event to a device however on calender in device its getting shown on each date upto the end date of the event
NSString *GoalDate = [[[DFDateFormatterFactory sharedFactory]
dateFormatterWithFormat:#"yyyy-MM-dd" andLocaleIdentifier:#"en_US"]
stringFromDate:self.datepicker.date];
[AppHelper saveToUserDefaults:GoalDate withKey:#"goalsdates"];
NSInteger dummyInteger = [[AppHelper userDefaultsForKey:#"event"]intValue];
if(dummyInteger!=0)
{
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (!granted)
{ return;
}
EKRecurrenceEnd *endRecurrence = nil;
endRecurrence = [EKRecurrenceEnd recurrenceEndWithEndDate:self.datepicker.date];
EKRecurrenceRule *recurrence;
if(dummyInteger==1)
{
recurrence= [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: EKRecurrenceFrequencyDaily
interval:1 daysOfTheWeek:nil daysOfTheMonth:nil monthsOfTheYear:nil weeksOfTheYear:nil daysOfTheYear:nil setPositions:nil end:endRecurrence];
}
if(dummyInteger==2)
{
recurrence = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: EKRecurrenceFrequencyWeekly interval:7 daysOfTheWeek:nil daysOfTheMonth:nil monthsOfTheYear:nil weeksOfTheYear:nil daysOfTheYear:nil setPositions:nil
end:endRecurrence];
}
if(dummyInteger==3)
{
recurrence = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: EKRecurrenceFrequencyWeekly interval:1 daysOfTheWeek:nil daysOfTheMonth:nil monthsOfTheYear:nil weeksOfTheYear:nil daysOfTheYear:nil setPositions:nil end:endRecurrence];
}
if(dummyInteger==4)
{
recurrence = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: EKRecurrenceFrequencyYearly interval:1 daysOfTheWeek:nil daysOfTheMonth:nil monthsOfTheYear:nil weeksOfTheYear:nil daysOfTheYear:nil setPositions:nil end:endRecurrence];
}
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = [AppHelper userDefaultsForKey:#"nameofagoal"];
event.allDay = false;
event.startDate =[NSDate date];
// event.endDate = [event.startDate dateByAddingTimeInterval:60*60*24*7]; //set 1 hour meeting
event.endDate = self.datepicker.date;
// event.endDate = endDate;
[event setCalendar:[store defaultCalendarForNewEvents]];
NSError *err = nil;
[event addRecurrenceRule: recurrence];
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
savedEventId = event.eventIdentifier; //this is so you can access this event later
}];
By default event kit adds event from start to end date. If your start and end date are different. Then it will show on all the days from start to end. If you want to show event only on start day and end day of event then you must have to add two events with same name but different ending dates.
You can also set allDay property of the event to YES. In this case event will not cover the whole screen if you are on the day view of calendar.
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;
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 can I use Objective-C to programmatically create an iCal event in the default calendar? I want to check whether the event already exists and set the button state accordingly.
An example of how to programmatically create an iCAL event in the default calendar, using Objective-C. The code checks if the event already exists, and sets the button state accordingly. Here is the code by #codeburger:
-(void)initCalendar {
// An array of 1 dictionary object, containing START and END values.
NSMutableArray* pvDict = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:PV_URL ]];
// Check if the private view event already exists in the default calendar.
// Then set the calendar button state.
// Get a entry point to the Calendar database.
self.store = [[EKEventStore alloc ] init ];
// Get an array of all the calendars.
NSArray *calendars = store.calendars;
// Get the default calendar, set by the user in preferences.
EKCalendar *defaultCal = store.defaultCalendarForNewEvents;
// Find out if this calendar is modifiable.
BOOL isDefaultCalModifiable = defaultCal.allowsContentModifications ;
// Create an event in the default calendar.
self.event = [ EKEvent eventWithEventStore:store ];
self.event.title = CHELSEA_SPACE ;
self.event.location = CHELSEA_ADDRESS ;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss.S"];
NSString *startString = [[ pvDict objectAtIndex:0] objectForKey:#"starts" ];
NSDate *dateStart = [dateFormatter dateFromString:startString];
NSString *endString = [[ pvDict objectAtIndex:0] objectForKey:#"ends" ];
NSDate *dateEnd = [dateFormatter dateFromString:endString];
self.event.startDate = dateStart;
self.event.endDate = dateEnd;
self.event.calendar = defaultCal ;
// Alternative code to add 2.5 hours to start time.
// [[NSDate alloc] initWithTimeInterval:9000 sinceDate:event.startDate];
// Search for events which match this date/time start and end.
// Compare the matched events by event TITLE.
NSPredicate *predicate = [store predicateForEventsWithStartDate:event.startDate
endDate:event.endDate calendars:calendars];
NSArray *matchingEvents = [store eventsMatchingPredicate:predicate];
self.calendarButton.enabled = NO;
if( ! isDefaultCalModifiable ) {
// The default calendar is not modifiable
return ;
}
if ( [ matchingEvents count ] > 0 ) {
// There are already event(s) which match this date/time start and end.
// Check if this event is the PV
EKEvent *anEvent;
int j;
for ( j=0; j < [ matchingEvents count]; j++) {
anEvent = [ matchingEvents objectAtIndex:j ] ;
if([ CHELSEA_SPACE isEqualToString: anEvent.title ]) {
// PV event already exists in calendar.
return;
}
}
[ anEvent release ];
}
self.calendarButton.enabled = YES;
[ pvDict release ];
}
-(void)addEventToCalendar:(id)sender {
NSError *error;
BOOL saved = [self.store saveEvent:self.event span:EKSpanThisEvent error:&error];
NSLog(#"Saved calendar event = %#\n", (saved ? #"YES" : #"NO"));
self.calendarButton.enabled = NO;
}
I've seen this question with no answer and felt like it should be edited giving full credit to #codeburger.
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
NSDate *date = [[NSDate alloc ]init];//today,s date
event.title = #"remainder";//title for your remainder
event.startDate=date;//start time of your remainder
event.endDate = [[NSDate alloc] initWithTimeInterval:1800 sinceDate:event.startDate];//end time of your remainder
NSTimeInterval interval = (60 *60)* -3 ;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:interval]; //Create object of alarm
[event addAlarm:alarm]; //Add alarm to your event
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
NSString *ical_event_id;
//save your event
if([eventStore saveEvent:event span:EKSpanThisEvent error:&err]){
ical_event_id = event.eventIdentifier;
NSLog(#"%#",ical_event_id);
}
for more info check this link
sample for EKEvent
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;
}
}
}
}