I want to cancel a UILocalnotification , when i cancel notification still the notification is being fired . I wanted to know do i have to call any delegate method in appdelegate to cancel notification .the code which i am using is executing correctly .but the notification is getting fired .
Should i use NSNotification center which has removeObserver method to cancel uilocalnotification.
Does UILocalnotification fires notification from the app or from the device.
UPDATE - This is how i am scheduling my notification
-(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;
}
Cancelling notification
- (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];
NSLog(#"remedyID : %d",remedyId);
NSLog(#"notifyId : %d",notifRemedyId);
if (remedyId == notifRemedyId) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
NSLog(#"Cancelling... After %d",[[[UIApplication sharedApplication]scheduledLocalNotifications]count]);
}
NSNotification center which has removeObserver method to cancel uilocalnotification.
NSNotificationCenter has nothing to do with UILocalNotification. I'm sorry that they both use "notification" somewhere in their names, but that is just coincidence really.
scheduledLocalNotifications will give you the list of all scheduled notifications and use
- (void)cancelLocalNotification:(UILocalNotification *)notification
or you can cancel them all using:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Edit :
NSString *notifRemedyId = #"notifRemedyId";
UILocalNotification *localnotif=[[UILocalNotification alloc]init];
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:#"kRemindMeNotificationRemedyIDKey", kRemindMeNotificationRemedyIDKey,YOUR_REMEDYID,#"notifRemedyId",nil];
localnotif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localnotif];
Cancel as :
for (UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[aNotif.userInfo objectForKey: kRemindMeNotificationRemedyIDKey] isEqualToString:#"kRemindMeNotificationRemedyIDKey"]) {
if (remedyId == [[aNotif.userInfo objectForKey: kRemindMeNotificationRemedyIDKey] intValue]) {
[[UIApplication sharedApplication] cancelLocalNotification:aNotif];
break;
}
}
}
Hope it helps you.
Related
I used Notification Alert for my app and used the below code
if(condition){
[defaults setBool:YES forKey:#"notificationIsActive"];
[defaults synchronize];
//self.message.text=#"Notifications Started";
NSTimeInterval interval;
interval = 5;
UILocalNotification* localNotification = [[UILocalNotification
alloc] init];
localNotification.fireDate = [NSDate
dateWithTimeIntervalSinceNow:interval]; //Enter the time here in
seconds.
localNotification.alertBody= #"Alert time";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval=
NSCalendarUnitDay;//NSCalendarUnitMinute;
//Repeating instructions here.
localNotification.soundName= UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
else
{
NSArray *arrayOfLocalNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications] ;
for (UILocalNotification *localNotification in arrayOfLocalNotifications) {
if ([localNotification.alertBody isEqualToString:#"Alert time"]) {
NSLog(#"the notification this is canceld is %#", localNotification.alertBody);
[[UIApplication sharedApplication] cancelLocalNotification:localNotification] ; // delete the notification from the system
}
}
}
Now problem is I got extra notifications showing this is message Users will see. I checked everything that there is no extra notification alert I added. Now what can I do? Please help..
EDIT:
One point is missing. I used that notification for testing in my app but later I removed that notification.
So I have managed to set up local notification in my app by doing so.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = text;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
notif.soundName = sound;
};
[app scheduleLocalNotification:notif];
}
inside of a method that is called
- (void)createDateNotification:(NSString*) title alertText: (NSString*)text timeToWait: (NSTimeInterval)time soundToPlay: (NSString*)sound;
and when I call that method, The notification runs just like expected. My problem is that in my game I want it to be when the user clickes on the local notification that it will run a method which now just does so
-(void)rewardUser {
NSLog(#"User rewarded")
}
but sometimes it may run a different method and I don't know how do do it. Anything from swift to objective c will be appreciated. Much thanks!
Override - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification in your AppDelegate and do your thing.
I managed to solve it by doing this. When creating the alert, I set the action to a public string in my class which is called action and as #songchenwen mentioned, I overrided the didReceiveLocalNotification to check if the action is equal to a number of variables and if so run a method for each one.
I called the mothod like this setting a string for the action
[self createReminderNotification:#"Give50Coins" messageTitle:#"t" messageBody:#"gfdhgsh" timeToWait:2 soundToPlay:#"audio.wav"];
And in the method I initialised the notification setting all the details.
NSDate *notifTime = [[NSDate date] dateByAddingTimeInterval:time];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notif = [[UILocalNotification alloc] init];
action = actionAfterNotifiy;
if (notif) {
notif.fireDate = notifTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.repeatInterval = 0;
notif.alertTitle = title;
notif.alertBody = message;
if (sound == nil) {
NSLog(#"default sound");
}
else {
NSLog(#"other sound");
};
}
[app scheduleLocalNotification: notif];
and in the - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification
I did this,
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if ([action isEqualToString:#"Give50Coins"]) {
NSLog(#"wheyy");
}
else {
//random stuff here
}
}
I'm developing application which acquire the functionalities of Local notification. When few conditions matched, i need to fire Local notifications. I'm done with firing local notification and actions then. But i need to show all fired notifications in 'Notifications Center' even application is foreground or background.
I'm use following code :
In didFinishLaunchingWithOptions method :
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
When few conditions matched :
for (int i = 0; i < [arrayNotif count]; i++) {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
[localNotif setAlertBody:[NSString stringWithFormat:#"%#", [[arrayNotif objectAtIndex:i] valueForKey:#"title"]]];
[localNotif setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[localNotif setTimeZone:[NSTimeZone defaultTimeZone]];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:[arrayNotif objectAtIndex:i] forKey:[NSString stringWithFormat:#"%#", [[arrayNotif objectAtIndex:i] valueForKey:#"id"]]];
[localNotif setUserInfo:dictionary];
localNotif.soundName = UILocalNotificationDefaultSoundName;
[localNotif setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
dictionary = nil;
}
I get all notifications by didReceiveLocalNotification: method only application is in foreground. Now, i want to show all notifications in Notification Center.
I am implementing local notifications in my iOS app. Actually, I have a implementation with a method when i have created a notification :
-(void)setAlarmAction: (NSDate *) notificationDay days: (NSNumber *) day alert : (NSNumber * ) priority name:(NSString * ) nameNotification {
NSDate *notificationDate = notificationDay;
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil) {
return;
}
localNotification.fireDate = notificationDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = [NSString stringWithFormat: #"Quedan %# dias" , day];
localNotification.alertAction = #"Ver Documento";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1; //aumenta en uno el numero de notificaciones
////////////
NSDictionary *infoDictionary = [NSDictionary dictionaryWithObject:#"notification" forKey:nameNotification]; //1º que se guarda , 2º con que clave
localNotification.userInfo = infoDictionary;
////////////
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:localNotification];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:nameNotification];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Get list of local notifications
NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for( UILocalNotification * local in localNotifications) {
NSLog(#"Notificacion: %# fecha :%#",local.alertBody,local.fireDate.description);
}
}
-(void) launchNotificacion:(Documento *)document {
self.txDate.text = document.text;
}
I want the app run in background and when it appear on the tabBar, i can push it and it go me to a concret view and launch a few data. I did it in the didFinishlaunchingWithOptions.
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//self.viewDocumentForm
VTDocumentFormViewController *VTDocument = [[VTDocumentFormViewController alloc] initWithNibName:#"VTDocumentFormViewController" bundle:nil];
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
[self.window.rootViewController presentViewController: VTDocument animated:YES completion:nil];
Documento *reminderDocument = [NSEntityDescription insertNewObjectForEntityForName:#"Documento" inManagedObjectContext:self.managedObjectContext];
reminderDocument = [notification.userInfo objectForKey: key ];
[self.viewDocumentForm launchNotificacion:reminderDocument];
application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}
// Override point for customization after application launch.
return YES;
}
But it doesn't work and i don't know the reason. Please, help.
didFinishLaunchingWithOptions: with UIApplicationLaunchOptionsLocalNotificationKey in launchOptions will be invoked only if app was suspended/killed before localNotification.fireDate reached.
If you'r app is just in background (not killed) or active you'll got
application:didReceiveLocalNotification: fired
Also i don't see in your didFinishLaunchingWithOptions: where did you register user notification settings (for iOS8)… smth like:
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]) {
UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge;
UIUserNotificationSettings *mySettings =
[UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
}
I've created a old uilocalnotification, now, I want to update it, I searched on Google but there are no way to update the local notification. So, I decided to cancel it and create a new local notication:
- (void) cancelLocalNotificationByUserInfo: (NSDictionary *)dictInfo
{
UIApplication *application = [UIApplication sharedApplication];
NSArray *notifArr = [application scheduledLocalNotifications];
for (int i=0; i<notifArr.count; i++)
{
UILocalNotification* theNotif = (UILocalNotification *)[notifArr objectAtIndex:i];
if ([theNotif.userInfo isEqual:dictInfo])
{
[application cancelLocalNotification:theNotif];
}
}
}
- (void) addLocalNotification: (NSDate *) fireDate soundName: (NSString *) soundName
alertBody: (NSString *) alertBody infoDict: (NSDictionary *)infoDict
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = fireDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = alertBody;
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.hasAction = YES;
localNotif.applicationIconBadgeNumber = 1;
localNotif.soundName = soundName;
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}
But, everytime, I execute the addLocalNotification method, the old local notification is fired immediately. Please help me!