I have some repeated actionable notifications, and when I tapped on button of some notification
(I mean this), I have to delete all the same notifications. For example, I have 4 already pushed notifications:
Not 1
Not 2
Not 1
Not 2
If I use actions of "Not 1", I need to delete all "Not 1", so, It will be like this
Not 2
Not 2
Can I do this?
[UIApplication sharedApplication].scheduledLocalNotifications]
gives me only scheduled notifications, but I need to delete already showed notifications, whitch isn't in this array.
You can save a unique value for key in your local notification's userinfo. Get all local notification, loop through the array and delete the particular notification.
Code as follows,
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:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
Related
I can't seem to find it and I'm not sure how to Google it. In my app I use background fetches to do checks and if there is new data, I send a notification to the user using UILocalNotification. Now how do I prevent the app from sending a new notification to the user if there is already one there? I'm now ending up with 5 of the same notifications when I don't look at my phone for some hours.
Thanks!
You can use UIApplication's property scheduledLocalNotifications
Here's the sample code:
NSMutableArray *notifications = [[NSMutableArray alloc] init]; [notifications addObject:notification]; myApp.scheduledLocalNotifications = notifications;
//Equivalent: [myApp setScheduledLocalNotifications:notifications];
UIApplication *myApp = [UIApplication sharedApplication];
NSArray *eventArray = [myApp scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[myApp cancelLocalNotification:oneEvent];
break;
}
}
NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
if ([localNotification.alertBody isEqualToString:savedTitle]) {
NSLog(#"the notification this is canceld is %#", localNotification.alertBody);
[[UIApplication sharedApplication] cancelLocalNotification:localNotification] ; // delete the notification from the system
}
}
Hope this would help figure out the solution.
The best way to avoid having to cancel something it in the first place is also to simply NOT sending it.
Find a way to know if the user has been notified before, and if he has, don't notify again :)
This is cleaner, more efficient, will last forever, and won't backfire, ever.
Also, this answers your question of "not sending a notification again" instead of sending it and cancelling afterwards, which isn't a good idea if you think about it.
I am working on a dummy project in xcode 6 and creating local notifications. I have created and deleted these local notifications.Now I want to edit a particular notification.
You cannot change an already scheduled notification.
You will have to cancel, and re-create it with the new data you need.
You can ask the current scheduled UILocalNotifications:
NSArray *scheduledNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
Loop the array and do a check if its the notification you need to change:
for (UILocalNotification *notification in scheduledNotifications)
{
//Get the ID you set when creating the notification
NSDictionary *userInfo = notification.userInfo;
NSNumber *someValueYouGaveWhenCreatingCouldBeAnIdentifierOfAnObject = [userInfo objectForKey:#"someKey"];
if (someValueYouGaveWhenCreatingCouldBeAnIdentifierOfAnObject == someCheckYouHaveToDoHere)
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
//Re-create the localnotification with new data and the someValueYouGaveWhenCreatingCouldBeAnIdentifierOfAnObject
break;
}
}
I'm using a UILocalNotification object to give notification to my application. Currently each time an event is generated i popup a notification.
notification.alertBody=#"Event Occurs 2";
notification.alertAction=#"Open";
[[UIApplication sharedApplication]presentLocalNotificationNow:notification];
But, since the events keep on happening, each time a new notification is generated.
Is there a way to update a notification, if it is already present and create a new notification if not present.
You can't update an already scheduled Local Notication. You can however, cancel it and reschedule a new one.
Cancel your local notification:
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:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling the specific local notification
[app cancelLocalNotification:oneEvent];
//Schedule your new "updated" local notification here.
break;
}
}
This will loop through all scheduled local notifications and delete the local notification you want deleted. Note, you'll need to set a unique property to each notification to distinguish between others (in the example above, it is assumed userInfo contains a unique "uid").
Thanks to KingofBliss for code above on how to delete specific local notifications.
It's not possible to update the notification but if you attach a dictionary with a key to the alert:
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:alarmID forKey:#"AlarmKey"];
// Set some extra info to your alarm
notification.userInfo = userInfo;
Then you can retrieve the local notification, cancel it and make a new one with updated content.
+ (UILocalNotification *)existingNotificationWithAlarmID:(NSString *)alarmID
{
for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[notification.userInfo objectForKey:#"AlarmKey"] isEqualToString:alarmID]) {
return notification;
}
}
return nil;
}
You cancel the notification like this:
- (void)cleanUpLocalNotificationWithAlarmID:(NSString *)alarmID
{
UILocalNotification *notification = [self existingNotificationWithAlarmID:alarmID];
if (notification) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
No, there is no way to modify a local notification that has been scheduled. You'll have to cancel the notification and schedule it again.
I have a multiple local notification which repeat every minutes.when local notification are arrive then i update the database.It's Work fine. But when we set multiple notification then It's fire time is Same.so both local notification simultaneously execute at same time.*This situation into my database update is not work properly.means first value reference data are updated *
//below set notification.
AlarmNotification = [[UILocalNotification alloc]init];
// AlarmNotification.fireDate = SetAlarmTime;
AlarmNotification.fireDate = AddMinutes;
AlarmNotification.repeatInterval = NSMinuteCalendarUnit;
AlarmNotification.alertBody =cloclListInsert.labelText;
AlarmNotification.timeZone = [NSTimeZone defaultTimeZone];
AlarmNotification.soundName =cloclListInsert.SelctAlaemToneDbStr;
NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
NSString *ClockIDStr = [NSString stringWithFormat:#"%i",cloclListInsert.ClockIDvalue];
[userDict setObject:ClockIDStr forKey:#"ClockID"];
AlarmNotification.userInfo = userDict;
[[UIApplication sharedApplication]scheduleLocalNotification:AlarmNotification];
delegate method in App Delegate
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSLog(#"notification.userInfo : %#",notification.userInfo);
NSString *SelectID= [notification.userInfo objectForKey:#"ClockID"];
NSLog(#"SelectID is : %#",SelectID);
NSLog(#"notification.userInfo : %#",notification.userInfo);
NotificationId = [SelectID integerValue];
NSLog(#"NotificationId is : %i",NotificationId);
clocklistobj.ClockIDvalue = NotificationId;
if ([sqldbobj getNotificationClockList:clocklistobj]) {
NotificationCount = clocklistobj.incrementTag;
NSLog(#"NotificationCount : %i",NotificationCount);
clocklistobj.incrementTag =NotificationCount +1;
//insert increment tag in counter variable
counter = clocklistobj.incrementTag;
NSLog(#"counter when receive notification in delegate method: %i",counter);
NSLog(#"NotificationCount +1 & clocklistobj.incrementTag : %i",clocklistobj.incrementTag);
//set brightness of device
SetBrightnessValue = (float) (clocklistobj.incrementTag *0.066666);
NSLog(#"SetBrightnessValue : %f",SetBrightnessValue);
[[UIScreen mainScreen] setBrightness:SetBrightnessValue];
//set music player & control volume
setPlayerVolume = (float) (clocklistobj.incrementTag *0.066666);
NSLog(#"set Player Volume : %f",setPlayerVolume);
[audioPlayer setVolume:setPlayerVolume];
//below start playing audio
[audioPlayer play];
//update database
[sqldbobj UpdateNotificationCount:clocklistobj];
NSLog(#" After update clocklistobj.incrementTag:%i",clocklistobj.incrementTag);
if (clocklistobj.incrementTag ==15 || clocklistobj.incrementTag >15) {
NSLog(#"Notification reach at limit");
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
// NSLog(#"eventArray : %#",eventArray);
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"ClockID"]];
NSInteger GetUid = [uid integerValue];
//here we cancell the particular notification
NSLog(#"Application is stoped clocklistobj.ClockIDvalue : %i", clocklistobj.ClockIDvalue);
if (GetUid ==clocklistobj.ClockIDvalue)
{
clocklistobj.soundisON = 0;
[sqldbobj UpdateAfteNotificationSwitchMakeOff:clocklistobj];
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}else {
NSLog(#"Notification is off");
}
}
}
Ok so what you can do is you can restrict the user from setting multiple alarm at the same time.
For doing so you have to call [[UIApplication sharedApplication] scheduledLocalNotifications], it will provide you all the notifications scheduled till now.
Then you can go through these notification and check for the notification.fireDate if it matches your current scheduling fireDate then you can show an alert to user by saying that 'There is another alarm scheduled at the same time.'.
My app allows users to set a number of reminders in the future. When the app lauches I want to know what reminders (notifications) have already been set.
Can I read back the notifications I have set or do I need to store in my app (e.g. Core Data or Plist)?
UIApplication has a property called scheduledLocalNotifications which returns an optional array containing elements of type UILocalNotification.
UIApplication.shared.scheduledLocalNotifications
For Swift 3.0 and Swift 4.0
don't forget to do import UserNotifications
This is working for iOS10+ and watchOS3+ since the class UNUserNotificationCenter is not available for older versions (link)
let center = UNUserNotificationCenter.current()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
center.getPendingNotificationRequests { (notifications) in
print("Count: \(notifications.count)")
for item in notifications {
print(item.content)
}
}
}
Scott is correct.
UIApplication's property scheduledLocalNotifications
Here's the code:
NSMutableArray *notifications = [[NSMutableArray alloc] init];
[notifications addObject:notification];
app.scheduledLocalNotifications = notifications;
//Equivalent: [app setScheduledLocalNotifications:notifications];
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:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
if ([localNotification.alertBody isEqualToString:savedTitle]) {
NSLog(#"the notification this is canceld is %#", localNotification.alertBody);
[[UIApplication sharedApplication] cancelLocalNotification:localNotification] ; // delete the notification from the system
}
}
For more info, check out this: scheduledLocalNotifications example UIApplication ios
#Scott Berrevoets gave the correct answer. To actually list them, it is simple to enumerate the objects in the array:
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(UILocalNotification *notification, NSUInteger idx, BOOL *stop) {
NSLog(#"Notification %lu: %#",(unsigned long)idx, notification);
}];
Swift 3.0.2:
UIApplication.shared.scheduledLocalNotifications
In iOS 10, using the new UserNotifications framework:
UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
print("Requests: \(notificationRequest)")
}
Swift 4
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (requests) in
for request in requests {
if request.identifier == "IDENTIFIER YOU'RE CHECKING IF EXISTS" {
//Notification already exists. Do stuff.
} else if request === requests.last {
//All requests have already been checked and notification with identifier wasn't found. Do stuff.
}
}
})
I used this to fix a bug where the same weekly notification was already set and being set again when the app would open, so it would keep resetting the timer to appear, which means it never did appear.
In Swift, to see all your currently scheduled local notifications printed in the console:
print(UIApplication.sharedApplication().scheduledLocalNotifications)