Cancelling a specific UILocalNotification - iphone

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.

Related

UILocalNotification is not getting cancelled

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

How 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.

How do I create a UILocalNotification that notifies every two minutes

So I'm basically trying to set an app that gives local notifications constantly.
So far I have:
- (void)scheduleNotification {
[reminderText resignFirstResponder];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Your building is ready!";
notif.alertAction = #"View";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSInteger index = [scheduleControl selectedSegmentIndex];
switch (index) {
case 1:
notif.repeatInterval = NSMinuteCalendarUnit;
break;
case 2:
notif.repeatInterval = NSMinuteCalendarUnit*2;
break;
default:
notif.repeatInterval = 0;
break;
}
NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
I'm trying to make it so I can get a notification every 2 minutes (when I set case 2) and every 1 minute (when I set case 1) to be notified. The only problem is... The *2 isn't working to make it get notified every 2 minutes. How would I go about making it so that it notifies every 2 minutes?
You can only use the defined calendar units in NSCalendarUnit when you are setting the repeatInterval property of a UILocalNotification. You can't use custom units or manipulate the units, so you won't be able to do what you want using the notification's repeat interval property.
To schedule notifications every 2 minutes, you will most likely want to schedule multiple notifications at different times (2 minutes apart). You can create a UILocalNotification, and then schedule it with:
[[UIApplication sharedApplication] scheduleLocalNotification: localNotification];
then modify the fireDate property (by adding your repeat interval), and then schedule it again with the same code. You can repeat this in a loop however many times you need to repeat the notification.

Custom Core Data accessors for transformable UILocalNotification

I have a transformable attribute on one of my entities, called reminder. It's a UILocalNotification.
Now, since I want to schedule it when it's added, and cancel it when removed, I would like to override the accessors to handle the scheduling and cancelling in there.
How would that look?
Thanks!
Are you actually persisting the UILocalNotification or are you using it as a transient property?
I wouldn't store it, rather UILocalNotification as a userInfo as a property. You can at a key/value pair to that dictionary with information about the owning entity. For instance:
You create a value for the key notificationID in the userInfo dictionary and set a attribute notificationID on your Core Data entity to the same value. That way, you just have to store an int or NSString in your store (which is preferable to transformable).
When you want to fetch your UILocalNotification again you can make an accessor on your Entity Class, something like:
- (void)createNotification
{
static NSUInteger kDeadlineWarningPeriod = 3600;
UILocalNotification *notification = [[UILocalNotification alloc] init];
…
self.notificationID = #"some generated ID";
[notification.userInfo setValue:self.notificationID forKey:#"notificationID"];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[notification release];
}
- (void)cancelNotification
{
// We search for the notification.
// The entity's ID will be stored in the notification's user info.
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UILocalNotification *notification = (UILocalNotification *)obj;
NSDictionary *userInfo = notification.userInfo;
NSString *notificationID = [userInfo valueForKey:#"notificationID"];
if ([notificationID isEqualToString:self.notificationID])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
*stop = YES;
self.notificationID = nil;
}
}];
}
Of course you can make an accessor for your notification in much the same way if you actually need access to the notification object.
Hope it helps.
UPDATE
So since you have a property you call reminder on you Entity (I'm guessing that it is a BOOL) it will look something like this:
// .h
#property (nonatomic, assign) BOOL reminder;
// .m
- (void)setReminder:(BOOL)reminder {
[self willAccessValueForKey#"reminder"];
BOOL hasReminder = [[self primitiveValueForKey:#"reminder"] booleanValue];
[self didAccessValueForKey:#"reminder"];
if (hasReminder && !reminder) {
[self cancelNotification];
}
else if (!hasReminder && reminder) {
[self createNotification];
}
if (reminder != hasReminder)
{
[self willChangeValueForKey:#"reminder"];
[self setPrimitiveValue:[NSNumber numberWithBool:reminder] forKey#"reminder"];
[self didChangeValueForKey:#"reminder"];
}
}
In fact you don't really have to store the "reminder" attribute at all, you can just check if the notificationID attribute is nil or not. That was the idea from my suggestion before.
I haven't checked the code above but I do something similar in two of my projects.
Remember you can get into trouble if you create more than 64 local notifications, since you are only allowed to make that many per app. So you might want to track how many you have before creating any new ones.
If you have only one notification for each object, then you could avoid having to store a notificationID and just use the objectId of the NSManagedObject in the Persistent store.
You can serialize and deserialize the objectId with the following lines of code:
[[self.objectID URIRepresentation] absoluteString]
and
[[self persistentStoreCoordinator] managedObjectIDForURIRepresentation:[NSURL URLWithString:[localNotif.userInfo objectForKey: kYourReminderNotificationKey]
here is the code edited:
- (void)createNotification
{
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = self.dateDue;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Alert body";
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:[[self.objectID URIRepresentation] absoluteString] forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
}
- (void)cancelNotification
{
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UILocalNotification *notification = (UILocalNotification *)obj;
NSDictionary *userInfo = notification.userInfo;
NSString *notificationID = [userInfo valueForKey:kRemindMeNotificationDataKey];
if ([notificationID isEqualToString:[[self.objectID URIRepresentation] absoluteString]])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
*stop = YES;
}
}];
}