Fire Date issue in local notification - iphone

I have a view controller which contains a field for user to enter date value.In contrast I have a field called "Remind Before Days" for the user to select when the notification should fire.If the remind before day is same day,then notification is set to fire on the date,but when the remind day is before 1 day,then notification should fire before one day the date set(specified).For this I have written a method called -(void)setNotification and here is the implementation code:
- (void)setNotification
{
//Set notification after confirmation of saved data
Class cls = NSClassFromString(#"UILocalNotification");
UILocalNotification *notif = [[cls alloc] init];
if (cls != nil)
{
textField = [self.fields objectAtIndex:3];
if (textField.text == #"Same Day")
{
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
}
else if(textField.text == #"1 Day")
{
NSDate *now = [datePicker date];
// set up date components
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];
[components setDay:-1];
// create a calendar to form date
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
notif.fireDate = newDate2;
notif.timeZone = [NSTimeZone defaultTimeZone];
}
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = textView.text;
notif.alertAction = #"View";
notif.soundName = #"lazy_afternoon.mp3";
notif.applicationIconBadgeNumber = 1;
textField = [self.fields objectAtIndex:1];
NSDictionary *userDict = [NSDictionary dictionaryWithObject:self.textField.text forKey:kReminder];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
Now as we are all aware that when the notification gets fired,the user clicks view.Then we show an alert,the implementation code is written in appDelegate.Here it is:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// For The Purpose Of Notification.
Class cls = NSClassFromString(#"UILocalNotification");
if (cls)
{
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
NSString *reminderText = [notification.userInfo objectForKey:kReminder];
[self.viewController showReminder:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
}
Now after local notification is received,we do the following i.e.:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo objectForKey:kReminder];
[self.viewController showReminder:reminderText];
}
Now I have set the -(void)setNotification action to right navigation right bar button item titled "Save" as follows:
-(IBAction)save:(id)sender
{
[self setNotification];
}
When I don't specify any condition for fire date i.e. simply assign as :
notif.fireDate = [datePicker date]; everything's fine with notification(no issues).
But when I do as the above i.e. condition for fire date,then the notification is not getting fired.Instead the alert is getting fired when I click save.Also when I quit the simulator,I could see some thread problem.I don't understand what's wrong with the code (implementation).I have gone through several links,also the apple documentation of UILocalNotification.Couldn't find out any property or method to set fire Date according to conditions.
I found out a method "repeatTimeInterval" which is relavant and applicable when a notification must be repeated weekly,yearly etc..which doesn't suit the requirement that the "date to be fired is this when the remind days in textField is this"
Can any one please guide me right,
Thanks all in advance :)

I believe if you check this link out you will find out. But from what I have seen the code you have provide is from this site anyway.
http://useyourloaf.com/blog/2010/7/31/adding-local-notifications-with-ios-4.html

I know I arrived a little late, but for me, the error on your code is here:
if (textField.text == #"Same Day")
Because you can't compare NSStrings using the operator ==. I think that if you use isEqualToString:(NSString*) it will work properly. It would be great if you could edit your original post and fix the code, so people looking for info about local notifications won't run into the same problem.

Related

Is it possible to have a Conditioned `firedate` for UILocalNotification?

I'm trying to have a conditioned firedate time for my local notifications, however when I tried these two ways it didn't fail but it still didn't work. So, I was wondering if I'm able to do such a thing?
Note: startTime and endTime are times from date pickers.
-(void) TEST {
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour = 3;
components.minute = (components.minute + 1) % 60;
components.second = 57;
NSDate *fire = [calendar dateFromComponents:components];
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
if (fire < startTime.date) {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: #"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}
if (fire > endTime.date) {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: #"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}}
OR
-(void) TEST {
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour = 3;
components.minute = (components.minute + 1) % 60;
components.second = 57;
NSDate *fire = [calendar dateFromComponents:components];
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
if (fire > startTime.date & fire < endTime.date) {
[[UIApplication sharedApplication] cancelAllLocalNotifications] ;
}
else {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: #"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}}
Thanks
If not, what would be the easiest way to make such a condition?
use the NSDate Compare: method instead of if(fire > startTime.date)
if([fire compare: startTime.date] == NSOrderedDescending) // if start is later in time than end
{
// do something
}
From the class reference:
If:
The receiver and anotherDate are exactly equal to each other, NSOrderedSame.
The receiver is later in time than anotherDate, NSOrderedDescending.
The receiver is earlier in time than anotherDate, NSOrderedAscending.
so for your condition
if (fire > startTime.date & fire < endTime.date) {
[[UIApplication sharedApplication] cancelAllLocalNotifications] ;
}
you can use
if([fire compare: startTime.date] == NSOrderedDescending && [fire compare: endTime.date]== NSOrderedAescending)
{
[[UIApplication sharedApplication] cancelAllLocalNotifications] ;
}
this will cancel the all local notifications if fire is between the selected start and end date
else {
// Fire the notifications
}
also have a look at the link this is similar to what you need link
what i, will try do do is, when the sleep Time starts,call a method eg: goingToSleep:, you can use
dispatch_later or performSelector:withObject:afterDelay: for that,
in goingToSleep:
NSArray* localNotifications = [[UIApplication sharedApplication]
scheduledLocalNotifications];
for (UILocalNotification *notification in localNotifications)
{
if([fire compare: startTime.date] == NSOrderedDescending &&
[fire compare: endTime.date]== NSOrderedAescending)
{
This is the important part
get all the properties of the notification
create a NSDictionary of those properties
Add the NSDictionary to an array
and save that array into a plist.(Save Array to Plist)
and then Cancel that notification using
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
then after SleepTime is over
, again call a method eg: wakingUp:
then in wakingUp:
read the array of NSDictionary we saved.
again Create UILocalnotifications using those same Properties.
this way, no UILocalNotifications will trigger during sleep time. one issue can be executing those methods, if the Application is not memory.
EDIT To have long Running Appicaions.

xcode : update icon badge daily

I looked at many pieces of codes but didn't get solution yet,
I simply need to get my app icon badge updated daily with some calendar (not gregorian) number of the day.
How can I do that?
I don't know how you would code it, but if you were going to submit such an app to the app store, apple wouldn't approve it. Apple's strict review guidelines can be frustrating, and like in this case, they limit functionality of your apps. Sorry :(
You obviously can't use repeating local notifications, because you want to specify an application badge number. Therefore you have to use one local notification for each day scheduled at midnight and with the appropriate badge number.
Because you can only schedule a maximum of 64 local notifications, you have to queue the notifications at each application launch.
This code isn't tested, there might be problems with daylight saving times, etc. (Works on iOS 4.2 or later, using ARC)
- (void) applicationDidBecomeActive:(UIApplication *)application {
NSUInteger startingDayAfterToday = [application.scheduledLocalNotifications count];
NSArray *localNotifications = [self localNotificationsStartingOnDayAfterToday:startingDayAfterToday];
NSArray *newScheduledNotifications = [application.scheduledLocalNotifications arrayByAddingObjectsFromArray:localNotifications];
[application setScheduledLocalNotifications:newScheduledNotifications];
}
- (NSArray *) localNotificationsStartingOnDayAfterToday:(NSUInteger)startingDayAfterToday {
NSMutableArray *localNotifications = [[NSMutableArray alloc] initWithCapacity:64 - startingDayAfterToday];
for (NSUInteger i = startingDayAfterToday; i < 64; i++) {
// Create a new local notification
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.hasAction = NO;
// Create today's midnight date
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // Could be other calendar, too
NSDateComponents *todayDateComponents = [calendar components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
NSDate *todayMidnight = [calendar dateFromComponents:todayDateComponents];
// Create the fire date
NSDateComponents *addedDaysComponents = [[NSDateComponents alloc] init];
addedDaysComponents.day = i;
NSDate *fireDate = [calendar dateByAddingComponents:addedDaysComponents toDate:todayMidnight options:0];
// Set the fire date and time zone
notification.fireDate = fireDate;
notification.timeZone = [NSTimeZone systemTimeZone];
// Set the badge number
NSDateComponents *fireDateComponents = [calendar components:NSDayCalendarUnit fromDate:fireDate];
notification.applicationIconBadgeNumber = fireDateComponents.day;
// We're done, add the notification to the array
[localNotifications addObject:notification];
}
return [localNotifications copy];
}

scheduled local notification is not being stored in the scheduledLocalNotification array

I am currently scheduling local notifications to appear once per day at 6PM if a user has not already opened the app that day. If the user has already loaded the application, then I want to cancel the notification for that day and schedule a new one for tomorrow at 6PM. The notification displays properly, however, when I try to iterate of the list of scheduled notifications (this is not the only local notification I have in the application), the [[UIApplication sharedApplication] scheduledLocalNotifications] array is always empty. Below is the code snippet that is giving me trouble:
// See if we need to create a local notification to tell the user that they can receive a daily reward
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications]; // <- This is always empty
// Iterate over all the pending notifications
for( int iter = 0; iter < [notifications count]; iter++ )
{
UILocalNotification* localNotification = [notifications objectAtIndex:iter];
if( [[localNotification.userInfo objectForKey:#"source"] isEqualToString:#"dailyReminder"] )
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
}
NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *nowComponents = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSSecondCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:serverDate];
int hour = [nowComponents hour];
int minute = [nowComponents minute];
int second = [nowComponents second];
int hoursToAdd = 18 - hour;
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setHour:hoursToAdd];
[comps setMinute:-minute];
[comps setSecond:-second];
NSDate *tomorrow6PM = [calendar dateByAddingComponents:comps
toDate:serverDate
options:0];
NSMutableDictionary* userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:#"dailyReminder" forKey:#"source"];
scheduleNotification(tomorrow6PM, NSLocalizedString(#"Come Back!", #"daily reminder notification message"), NSLocalizedString(#"Launch", #"daily reminder notification button text"), [UIApplication sharedApplication].applicationIconBadgeNumber+1, userInfo);
the scheduleNotification function is straightforward and just constructs a local notification:
void scheduleNotification(NSDate* fireIn, NSString* bodyText, NSString* alertText, NSUInteger badgeCount, NSMutableDictionary* userInfo)
{
static int appCount = 0;
appCount += 1;
if(!isLocalNotificationEnabled())
return;
Class localNotificationClass = NSClassFromString(#"UILocalNotification");
UILocalNotification* localNotification = [[localNotificationClass alloc] init];
if(!localNotification)
return;
localNotification.fireDate = fireIn;
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.alertBody = bodyText;
localNotification.alertAction = alertText;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = badgeCount;
localNotification.userInfo = userInfo;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
}
I don't understand why the array of local notifications is always empty. Like I said before the notifications display at the correct time, so they are getting scheduled. Any help is appreciated.
Having similar issues right now. My guess here is that iOS does not schedule the notifications immediately but only at the end of the current run loop. I am running into these problems when setting the scheduledLocalNotifications property several times in the same run loop and changes don't seem to be updated accordingly. I think I will just keep a copy of the local notifications array myself and only set scheduledLocalNotifications and never read it.
localNotification.fireDate = fireIn;
in this line check wheather "fireIn" is object of NSDate or NSString.
If it's NSString convert it into NSDate object with help of NSDateformatter and then assing it to localNotification fireDate.
I was facing same problem previously and resolved it with above mentioned steps.
if the schedule has invalid fire date, it will not get scheduled and result empty array returned, because there never has a valid one schedule, try to print out your localNotification like below, you may find out the problem.
NSLog(#"Notification--->: %#", localNotification);

how to compare the array values and check it with the current date and set it ti the notification firedate

i am using an user defaults which contains array of dates .in this array i am storing all the dates selected from the date picker.i now want to compare each of these dates with the current date .when the date matches with the current date the notification should be shown .i have done the code for traversing array but it is not working it does not match the date with the current date.And does not display the notification at the proper time.
This is my code:
-(void)scheduleNotification
{
[[UIApplication sharedApplication]cancelAllLocalNotifications];
timepicker = [[TTimePickerController alloc]init];
//this is my new code.
NSDate *now = [NSDate date];
NSMutableArray *array = [[NSUserDefaults standardUserDefaults]objectForKey:#"time"];
//array is my array where i am saving all the the userdefaults objects
for (NSDate *date in array)
{
//here i am comparing my date object with current date object
if ([date isEqualToDate:now])
{
itemDate = date;
NSLog(#"%#",itemDate);
}
}
Class cls = NSClassFromString(#"UILocalNotification");
if (cls!= nil) {
UILocalNotification *notif = [[cls alloc]init];
//in the notification firedate property i am setting the itemdate.
notif.fireDate = itemDate;
[app.dateFormatter setDateFormat:#"hh:mm a"];
newstring = [app.dateFormatter stringFromDate:notif.fireDate];
NSLog(#"new fire date:%#",newstring);
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Alarm";
notif.alertAction = #"View";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber=1;
notif.repeatInterval = 0;
[[UIApplication sharedApplication]scheduleLocalNotification:notif];
[notif release];
}
}
//but the problem the date is not getting checked properly and notification is not displayed at proper time.
You should remove this line from your code and it will work fine.
If you call this function, all your old notifications are canceled.
[[UIApplication sharedApplication]cancelAllLocalNotifications];

Fire a method ever 24 hours

I am trying to fire a method once a day at a given time. I've tried a few things but I can't really make it work. any advice would be appreciated. Also, it would be ideal if it would fire regardless of if the app is open or not. Is this possible?
UILocalNotification will let you fire a notification (but not a method) when your app is running in the background, or will call a delegate method you implement (application:didReceiveLocalNotification:) if the app is running in the foreground, or will call a method you must implement (application:didFinishLaunchingWithOptions:) when the user responds to the alert. Other than this, you will not be able to call a method when the app is not in the foreground, you will only be able to fire the the notification (which can display the badge, play a sound, etc).
By the way, consider filing a bug report with apple if this is a feature you want. I would like the ability to run methods in the background based on local notifications, without waiting for the user to respond first.
See Apple's example code:
- (void)scheduleNotificationWithItem:(ToDoItem *)item interval:(int)minutesBefore {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"%# in %i minutes.", nil),
item.eventName, minutesBefore];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}