How to tell which local notification has been received? Objective - C - iphone

I have this piece of code which calls a different NSLog statement depending on which local notification has been received:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
if (notification == automaticBackupNotification)
{
NSLog(#"Backup notification received.");
}
else
{
NSLog(#"Did receive notification: %#, set for date:%# .", notification.alertBody, notification.fireDate);
}
}
And I use this method to schedule the notification in another class:
- (IBAction)automaticValueChanged {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (automaticSwitch.isOn){
[defaults setValue:#"1" forKey:#"automatic"];
//schedule notification
//Set up the local notification
appDelegate.automaticBackupNotification = [[UILocalNotification alloc] init];
if(appDelegate.automaticBackupNotification){
//Repeat the notification according to frequency
if ([backupFrequencyLabel.text isEqualToString:#"Daily"]) {
appDelegate.automaticBackupNotification.repeatInterval = NSDayCalendarUnit;
}
if ([backupFrequencyLabel.text isEqualToString:#"Weekly"]) {
appDelegate.automaticBackupNotification.repeatInterval = NSWeekCalendarUnit;
}
else {
appDelegate.automaticBackupNotification.repeatInterval = NSMonthCalendarUnit;
}
//Set fire date to alert time
NSCalendar *calendar = appDelegate.automaticBackupNotification.repeatCalendar;
if (!calendar) {
calendar = [NSCalendar currentCalendar];
}
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
//NSDate *nextFireDate = [calendar dateByAddingComponents:components toDate:[NSDate date] options:0];
//appDelegate.automaticBackupNotification.fireDate = nextFireDate;
appDelegate.automaticBackupNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20.0];
//Set time zone to default
appDelegate.automaticBackupNotification.timeZone = [NSTimeZone defaultTimeZone];
// schedule notification
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:appDelegate.automaticBackupNotification];
NSLog(#"Backup Fire Date: %#", appDelegate.automaticBackupNotification.fireDate);
}
}
else {
[defaults setValue:#"0" forKey:#"automatic"];
if(appDelegate.automaticBackupNotification){
[[UIApplication sharedApplication] cancelLocalNotification:appDelegate.automaticBackupNotification];
}
}
[defaults synchronize];
}
However, when the application delegate receives the notification it fires the 'else' part of the conditional. Is there any way I can tell between the different notifications? Or am I doing something wrong?
Cheers,
Tysin

NSNotification object has property, which called userInfo. It is a NSDictionary, you can set some values where you create the notification and check for them where you receive it.

Just try to set userInfo property of your UILocalNotification, like this,
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"YOUROBJECT" forKey:#"TESTKEY"];
YOURNOTIFICATION.userInfo = userDict;
and when UILocalNotification fires this methods will be called,
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSDictionary *dict = [notification userInfo];
id obj = [dict objectForKey:#"TESTKEY"];
}
Based on userInfo you set at the time of setting UILocalNotification, You can find out which notification got called.

I personnaly use the notification name to know which notification push or have been received
//add local observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(mathodCalled:) name:[NSSTring StringWithFormat :#"plop"] object:nil];
...
//push an event manually
[[NSNotificationCenter defaultCenter] postNotificationName:eventName object:[NSSTring StringWithFormat :#"plop"]];
...
- (void)methodCalled :(NSNotification*)aNotification{
if([aNotification.name isEqualToString:#"plop"]){
// do something
}
}

Related

How to prevent cancel all the local notifications. Cancel Single notification nor works

I have a table view as follow i did set reminders for each cell using corresponding switch on
-(IBAction)switchingbtn:(id)sender
{
UISwitch *onoff = (UISwitch *) sender;
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if(onoff.on)
{
NSLog(#"Shedule notification");
int tagValue=[sender tag];
NSMutableDictionary *dict = (NSMutableDictionary *)[alarmsArray objectAtIndex:tagValue];
NSDate *firedate = [dict objectForKey:#"date"];
NSLog(#"fire date is %#", firedate);
localNotif.fireDate = firedate;
localNotif.alertBody = #"Start Exercise";
localNotif.applicationIconBadgeNumber = 0;
// localNotif.timeZone =[NSTimeZone timeZoneForSecondsFromGMT:0];
localNotif.timeZone = [NSTimeZone systemTimeZone];
localNotif.repeatInterval = kCFCalendarUnitDay;
// [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; //**Not working**
[localNotif release];
}
No i need to cancel a preticular 1 noftication for ex 3rd swich cancels 3rd notification
else
{
// Cancel a notification not works
// [[UIApplication sharedApplication] cancelLocalNotification:localNotif];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSLog(#"cancel notification");
}
The best way to cancel single notification so far, is to create an notication that has a userInfo dictionary, in this dictionary you could add a notification ID value for an id key. You keep track of the notifications ID (storing in a plist, sql database, etc) and when you need to delete a notification you just need to ask the UIApplication instance for the scheduled notif and filter by the ID, when you find the match you just need to send the cancel method for that notification.
here is the code which you wanted
- (void)CancelExistingNotification {
//cancel alarm
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:#"notificationID"]];
if ([uid isEqualToString:[NSString stringWithFormat:#"%i",self.notificationID]])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
"self.notificationID" comes from a property on a custom object like alarmObject which are loaded with the help NSUserDefaults application wide.

How to increment application badge number for recurring local notification (iPhone)

I've setup a local notification that repeats every minute, however I need the application badge number to increment each time. When I run it at the moment it doesn't seem to increase, it just stays a 1. Please can someone help me out?
Here is how I create the notifications:
// Create the UILocalNotification
UILocalNotification *myNotification = [[UILocalNotification alloc] init];
myNotification.alertBody = #"Blah blah blah...";
myNotification.alertAction = #"Blah";
myNotification.soundName = UILocalNotificationDefaultSoundName;
myNotification.applicationIconBadgeNumber++;
myNotification.timeZone = [NSTimeZone defaultTimeZone];
myNotification.repeatInterval = NSMinuteCalendarUnit;
myNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:30];
[[UIApplication sharedApplication] scheduleLocalNotification:myNotification];
After doing lot's of research I figured out the solution is that there is no solution:
iPhone: Incrementing the application badge through a local notification
It is not possible to update dynamically the badge number with local notifications while your app is in the background. You have to use push notifications.
If you use an outside service such as Parse for Push, this should be easily done. Just increment Parses badge number when a local notification is fired. Although, this is a special case.
While there's no simple applicationIconBadgeNumber++ method, as BFar mentioned, you can achieve what you're asking by updating all of the scheduled UILocalNotifications' applicationIconBadgeNumbers whenever a notification is added or removed.
While this won't work if you have notices that use repeatInterval, as long as you call scheduleNotification and decrementBadgeNumber at the right times, the class below should do the trick.
#implementation NotificationScheduler
+ (void) scheduleNotification:(NSString*)message date:(NSDate*)date {
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification) {
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = message;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = [self getExpectedApplicationIconBadgeNumber:date];
[app scheduleLocalNotification:notification];
[self updateBadgeCountsForQueuedNotifiations];
}
}
+ (void) decrementBadgeNumber:(long)amount {
[self setCurrentBadgeNumber:([self getCurrentBadgeNumber] - amount)];
[self updateBadgeCountsForQueuedNotifiations];
}
+ (long) getExpectedApplicationIconBadgeNumber:(NSDate*)notificationDate {
long number = [self getCurrentBadgeNumber];
for (UILocalNotification *notice in [self getScheduledLocalNotifications]) {
if (notice.fireDate <= notificationDate) {
number++;
}
}
return number;
}
+ (void) updateBadgeCountsForScheduledNotifiations {
long expectedBadgeNumber = [self getCurrentBadgeNumber];
NSArray *allLocalNotifications = [self getScheduledLocalNotifications];
for (UILocalNotification *notice in allLocalNotifications) {
expectedBadgeNumber++;
notice.applicationIconBadgeNumber = expectedBadgeNumber;
}
[[UIApplication sharedApplication] setScheduledLocalNotifications:allLocalNotifications];
}
+ (long) getCurrentBadgeNumber {
return [UIApplication sharedApplication].applicationIconBadgeNumber;
}
+ (void) setCurrentBadgeNumber:(long)number {
[UIApplication sharedApplication].applicationIconBadgeNumber = number;
}
+ (NSArray*) getScheduledLocalNotifications {
NSSortDescriptor * fireDateDesc = [NSSortDescriptor sortDescriptorWithKey:#"fireDate" ascending:YES];
return [[[UIApplication sharedApplication] scheduledLocalNotifications] sortedArrayUsingDescriptors:#[fireDateDesc]];
}
#end
I was able to do it using the following line while schedule the local notification
localNotification.applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
and on the other end in the appdelegate
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber -= 1;
}
Try something like:
int plusOne = [myNotification.applicationIconBadgeNumber intValue];
plusOne++;
myNotification.applicationIconBadgeNumber = plusOne;
This should work.
myNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
Try this ... it worked for me in simple scenario ...
notification.applicationIconBadgeNumber = [UIApplication sharedApplication].scheduledLocalNotifications.count + 1;
And don't forget to set badge icon back to 0 when app launch.

Cancelling a specific UILocalNotification

I have this code for local notification, and I have a scheduleNotification and clearNotification using my own method. These are the codes:
- (void)clearNotification {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (void)scheduleNotification {
[reminderText resignFirstResponder];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [[datePicker date] dateByAddingTimeInterval:-30];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Evaluation Planner";
notif.alertAction = #"Details";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
These codes works well, but now I want to know how do I know which notification object will it delete. I would like to create an ID for a notification, meaning, one ID is equivalent to one notification. But I don't know at which part I should do that. Plus I need to find a way to include all this to be in a plist.
Hope somebody can help me. Thanks.
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (UILocalNotification *not in notifications) {
NSString *dateString=[not.userInfo valueForKey:#"EndDate"];
if([dateString isEqualToString:#"CompareString"])
{
[[UIApplication sharedApplication] cancelLocalNotification:not];
}
}
Give user info whenever you create local notification (this is a key-value pair).
Iterate through notifications (it contains All Local Notifications) and compare value for the known key. In the above example I am using EndDate as the key and CompareString as the value.
Its Working Fine With Me.
Cheers..
(void)cancelLocalNotification:(NSString*)notificationID
{
// UILocalNotification *cancelThisNotification = nil;
// BOOL hasNotification = NO;
for (int j =0;j<[[[UIApplication sharedApplication]scheduledLocalNotifications]count]; j++)
{
UILocalNotification *someNotification = [[[UIApplication sharedApplication]scheduledLocalNotifications]objectAtIndex:j];
if([[someNotification.userInfo objectForKey:#"drdid"] isEqualToString:notificationID])
{
NSLog(#"id,notificationID(App) %# %# ",[someNotification.userInfo objectForKey:#"drdid"],notificationID);
NSLog(#"canceled notifications %#",someNotification);
[[UIApplication sharedApplication] cancelLocalNotification:someNotification];
}
}
}
I would suggest using the userInfo property on UILocalNotification, as others have mentioned. A simpler implementation that the accepted answer would be:
for(UILocalNotification* notification in [[UIApplication sharedApplication]scheduledLocalNotifications])
{
if([[notification.userInfo objectForKey:#"notification_identifier"] isEqualToString:#"notification_001"])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
A for loop like this is much simpler. I'm not sure if it's more or less optimal, but it's certainly easier to read, and I assume you only have a few notifications to loop through anyway.

iPhone: UILocalNotification doesn't repeat the notification

I am trying to use UILocalNotification in my project. I want my application to get notified every 5 seconds (non stop) in the background. I am trying the following code. It is notifying my application only for the first time after 5 seconds, after installed. I want it to be notified continuously every 5 seconds without stop. How can i achieve it?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
// Initiating notification at app startup
[self InitiateLocalNotification];
return YES;
}
-(void) InitiateLocalNotification
{
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5];
UILocalNotification *notify = [ [UILocalNotification alloc] init ];
notify.fireDate = notificationDate;
//notify.applicationIconBadgeNumber = 1;
notify.soundName = UILocalNotificationDefaultSoundName;
notify.timeZone = [NSTimeZone defaultTimeZone];
//notify.alertBody = #"Local notification test";
//notify.repeatInterval = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"notifiValue" forKey:#"notifiKey"];
notify.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
[notify release];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
}
I think, you need to register for the notification again if you receive any,
your code could be :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ // Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
// Initiating notification at app startup
[self InitiateLocalNotification];
return YES;
}
-(void) InitiateLocalNotification
{
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5];
UILocalNotification *notify = [ [UILocalNotification alloc] init ];
notify.fireDate = notificationDate;
//notify.applicationIconBadgeNumber = 1;
notify.soundName = UILocalNotificationDefaultSoundName;
notify.timeZone = [NSTimeZone defaultTimeZone];
//notify.alertBody = #"Local notification test";
//notify.repeatInterval = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"notifiValue" forKey:#"notifiKey"]; notify.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
[notify release];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// Need to register again
[self InitiateLocalNotification];
}
You are only calling
[self InitiateLocalNotification];
once, and therefore only scheduling one notification.
You must schedule each notification that you wish to receive (schedule notification 5 seconds from now, 10 seconds from now ... etc), since you don't have that kind of control over the repeat interval.
A solution would be to schedule the next one when you receive a notification, but that won't result in notifications scheduled exactly 5 seconds apart.

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;
}
}
}
}