I have about 60 local notifications in different switches but when I try it and apply more than one switch, it runs only for the last one.
Here's my code:
-(IBAction)theSwitch:(id)sender{
NSUserDefaults *defaultsB = [NSUserDefaults standardUserDefaults];
if (switcher.on == 1) {
NSCalendar *gregCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponent = [gregCalendar components:NSYearCalendarUnit | NSWeekCalendarUnit fromDate:[NSDate date]];
[dateComponent setWeekday:1]; // For sunday
[dateComponent setHour:16];
[dateComponent setMinute:30];
NSDate *fireDate = [gregCalendar dateFromComponents:dateComponent];
UILocalNotification *notification = [[UILocalNotification alloc]init];
[notification setAlertBody:textClass1.text];
[notification setFireDate:fireDate];
notification.soundName = #"bells.mp3";
notification.repeatInterval = NSWeekCalendarUnit;
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[defaultsB setObject:#"ON" forKey:#"SwitchState"];
}
else { UIApplication *app=[UIApplication sharedApplication];
[app cancelAllLocalNotifications];
[defaultsB setObject:#"OFF" forKey:#"SwitchStateOFF"];
}
}
Related
I'm developing an application where I need to set the reminder for a particular day. I'm Using Local notification and finding the date of selected Day of current week.
this is my code:
In viewController.m
NSArray* components12 = [self.LblTime.text componentsSeparatedByString:#":"];
NSString *Hours = [components12 objectAtIndex:0];
NSString *Minutes =[components12 objectAtIndex:1];
NSDate *currentDate = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianCalendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDateComponents *components = [gregorianCalendar components:(NSYearCalendarUnit| NSMonthCalendarUnit
| NSDayCalendarUnit| NSWeekdayCalendarUnit|NSWeekCalendarUnit) fromDate:currentDate];
NSLog(#"Current week day number %ld",(long)[components weekday]);
NSLog(#"Current week number %ld",(long)[components week]);
NSLog(#"Current month's day %ld",(long)[components day]);
NSLog(#"Current month %ld",(long)[components month]);
NSLog(#"Current year %ld",(long)[components year]);
NSDateComponents *dt=[[NSDateComponents alloc]init];
//Passing the Time (hours and minutes ) and Selected day with date
[dt setHour: [Hours integerValue]];
[dt setMinute:[Minutes integerValue]];
[dt setSecond:0];
[dt setWeek:[components week]];
[dt setWeekday:selecteddayValue];/// set the week Selected ay from picker
[dt setMonth:[components month]];
[dt setYear:[components year]];
NSDate *Date=[gregorianCalendar dateFromComponents:dt];// get the date of selected day of week
NSLog(#"Sunday date :%#",Date);
//Adding the reminder through Local notifiction
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate =Date;
localNotification.alertBody = #"Ready For Next Workout!";
localNotification.soundName = UILocalNotificationDefaultSoundName;
// localNotification.applicationIconBadgeNumber = 1; // increment
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:#"Object 1", #"Key 1", #"Object 2", #"Key 2", nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self showAlert:#"Reminder set Successfully"];
in appDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
// Handle launching from a notification
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
Now I'm not receiving the notification. Anyone please help for this.that would be very apperitiate.
if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
}
I have the following which I believe from the apple documentation here is all I need to have a category for UILocalNotification:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIMutableUserNotificationAction *acceptAction =
[[UIMutableUserNotificationAction alloc] init];
// Define an ID string to be passed back to your app when you handle the action
acceptAction.identifier = #"ACCEPT_IDENTIFIER";
// Localized string displayed in the action button
acceptAction.title = #"Accept";
// If you need to show UI, choose foreground
acceptAction.activationMode = UIUserNotificationActivationModeBackground;
// Destructive actions display in red
acceptAction.destructive = NO;
// Set whether the action requires the user to authenticate
acceptAction.authenticationRequired = NO;
// First create the category
UIMutableUserNotificationCategory *inviteCategory =
[[UIMutableUserNotificationCategory alloc] init];
// Identifier to include in your push payload and local notification
inviteCategory.identifier = #"INVITE_CATEGORY";
// Add the actions to the category and set the action context
[inviteCategory setActions:#[acceptAction]
forContext:UIUserNotificationActionContextDefault];
// Set the actions to present in a minimal context
[inviteCategory setActions:#[acceptAction]
forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(#"Recieved Notification %#",localNotif);
}
return YES;
}
Here is how I construct my local notification:
NSDate *dateChosen = [self.reminderDatePicker date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:dateChosen];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
// NSCalendar *calendar = [NSCalendar currentCalendar];
// NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay: 3];
[components setMonth: 7];
[components setYear: 2012];
[components setHour: hour];
[components setMinute: minute];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = dateToFire;
[localNotification setRepeatInterval: kCFCalendarUnitDay];
NSLog(#"Notification will be shown on: %# ",localNotification.fireDate);
localNotification.userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:self.dayPeriod, #"name", nil];
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = alertMessage;
localNotification.alertAction = NSLocalizedString(#"View details", nil);
localNotification.repeatInterval = NSDayCalendarUnit;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
It just shows the default notification with a dismiss button and not my accept button.
How can I get this "accept" button to show on my local notification?
The one thing that your missing in your main body of code for UILocalNotification is explicitly telling it to be a category based notification.
Add the category property to your notification:
localNotification.category = #"INVITE_CATEGORY";
The local notification never appeared. Can somebody tell me why?
- (IBAction)addReminder:(id)sender {
self.datePicker.timeZone = [NSTimeZone timeZoneWithName: #"Asia/Tokyo"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *formatedDate = [dateFormatter stringFromDate:self.datePicker.date];
NSLog(#"formatedDate>>>>>:%#", formatedDate);
NSDate *date = [dateFormatter dateFromString:formatedDate];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
NSLog(#"Setting a reminder for %#", localeDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif. fireDate = localeDate;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.alertBody = #"ZEIT!";
localNotif.alertAction = #"Show me the Timer!";
localNotif.timeZone = zone;
localNotif.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] +1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
Result:
formatedDate>>>>>:2015-08-09 23:32:00 Setting a reminder for 2015-08-09 23:32:00 +0000
Make sure you are requesting permission from the user to show notifications.
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
To : kmcgrady , thanks for your answer, but i tried this and it worked
NSDate *now=[NSDate new];
localNotif.fireDate=[now dateByAddingTimeInterval:12];
This question already has an answer here:
IOS Cancelling Local Notifications
(1 answer)
Closed 8 years ago.
I am using Local Notifications. I want to delete already scheduled notifications.I don't know where to write the code.Here is my code ..
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = self.selectedDate;
NSLog(#" self.selectedDate %#", self.selectedDate);
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
NSLog(#"itemDate %#",itemDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
NSLog(#"itemDate %#", localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [_titleTextFieldObj text];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber =[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSLog(#" localNotif.applicationIconBadgeNumber ++ %ld", (long)localNotif.applicationIconBadgeNumber );
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[_titleTextFieldObj text] forKey:#"someKey"];
localNotif.userInfo = infoDict;
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
//UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
NSLog(#"notif %#",notificationArray);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
Here I'm writing the removing of notification....
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
application.applicationIconBadgeNumber=1;
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;
NSLog(#"userInfoCurrent %#",userInfoCurrent);
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"uid"]];
NSLog(#"uid %#",uid);
if ([uid isEqualToString:[notification.userInfo objectForKey:#"someKey"]])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
if (notification) {
NSLog(#"notify %#",notification);
NSString *custom=[notification.userInfo objectForKey:#"someKey"];
NSLog(#"custom %#",custom);
NSString *newString = [custom stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"newString %#",newString);
NSLog(#"custmky%#",notification.description);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message" message:newString delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
alert.delegate=self;
[alert show];
}
}
I am new to UILocalNotifications and Objective-c. Can anyone please help me ....
You can cancel a UILocationNotification either by comparing fire dates to already scheduled UILocalNotifications or using its body.
An example of canceling by fire date:
UIApplication *application = [UIApplication sharedApplication];
NSDate *dateToCancel = nil; // Set this to the date you want to cancel
for (UILocalNotification *notification in [application scheduledLocalNotifications])
{
if (notification.fireDate == dateToCancel)
{
[application cancelLocalNotification:notification];
}
}
Now if you have a notification pointer you can just call the cancel local notification without needing to loop through already scheduled notifications. If you want you can also add an Id tag to the notification through key-object methods.
No matter in which class that code will lay, it's anywhere using UIApplication singleton...
You can cancel all notification using:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
If you want to remove a particular notification, you can use userinfo of notification object, when you create a local notification add a unique ID to that. Later you can use that ID for removing local notification.
For that you can use the following code:
NSString *notificationId = #"id_to_cancel";
UILocalNotification *notification = nil;
for(UILocalNotification *notify in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
if([notify.userInfo objectForKey:#"ID"] isEqualToString:notificationId ])
{
notification = notify;
break;
}
}
[[UIApplication sharedApplication] cancelLocalNotification:notification];
This question already has answers here:
Removing UILocalNotification from notification tray programmatically
(7 answers)
Closed 8 years ago.
I am using UILocalNotifications in my app.Now my requirement is the local notification should be cancelled after it’s scheduled.
Here my Code…
-(void)LocalNotificationMethod{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = self.selectedDate;
NSLog(#" self.selectedDate %#", self.selectedDate);
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
NSLog(#"itemDate %#",itemDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
NSLog(#"itemDate %#", localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [_titleTextFieldObj text];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber =[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSLog(#" localNotif.applicationIconBadgeNumber ++ %ld", (long)localNotif.applicationIconBadgeNumber );
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[_titleTextFieldObj text] forKey:#"someKey"];
localNotif.userInfo = infoDict;
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
//UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
NSLog(#"notif %#",notificationArray);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
**In Appdelegate.m i wrote the code like…**
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
application.applicationIconBadgeNumber=1;
if (notification) {
NSLog(#"notify %#",notification);
NSString *custom=[notification.userInfo objectForKey:#"someKey"];
NSLog(#"custom %#",custom);
NSString *newString = [custom stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"newString %#",newString);
NSLog(#"custmky%#",notification.description);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message" message:newString delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
alert.delegate=self;
[alert show];
}
//UIApplication *application = [UIApplication sharedApplication];
NSString *notificationId = #"id_to_cancel";
//UILocalNotification *notification = nil;
for(UILocalNotification *notify in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
if([[notify.userInfo objectForKey:#"someKey"] isEqualToString:notificationId ])
{
notification = notify;
break;
}
}
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
but it is not going into the loop …
I am new to this concept.Can anyone please help me to resolve this….
Thanks in advance.
You want to cancel a scheduled notification based on receiving another notification, if it is the case you need to put the loop before showing the Alert else your loop will never be executed. or in case you need to cancel/or not notification based button that will be taped in your AlertView you can put that code in your alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
for(UILocalNotification *notify in [[UIApplication sharedApplication] scheduledLocalNotifications]){
if([[notify.userInfo objectForKey:#"someKey"] isEqualToString:#"someValue"]) {
[[UIApplication sharedApplication] cancelLocalNotification:notify];
break;
}
}
}
By Default all UILocalNotification is OneTime so it cancel automatically after its fireDate
And looks like you are trying to get same UILocalNotification.
Please try putting same code at different place you will get all your Scheduled Notifications Or try to get all Scheduled Notifications before fireDate.