My remainder IPhone application getting delayed in seconds - iphone

I have made a remainder application using UIDatePicker and NSLocalNotification. The remainder app is ready and is working, but the remainder gets triggered some seconds later each time.
Here is the code:
-(void)addRemainder
{
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
dateform.dateFormat = #"dd-MM-yyyy HH:mm";
NSString *formattedDate = [dateform stringFromDate:datePicker.date];
date=[dateform dateFromString:formattedDate];
str=[dateform stringFromDate:date];
if(textField1.text!=nil)
{
notification = [[UILocalNotification alloc] init];
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = textField1.text;
notification.alertAction=#"Show me the item";
notification.soundName = UILocalNotificationDefaultSoundName;
NSUInteger nextBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count] + 1;
notification.applicationIconBadgeNumber = nextBadgeNumber;
notification.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
if ([remainderr isEqualToString:#"edit"])
{
[remainder replaceObjectAtIndex:([index integerValue]) withObject:textField1.text];
[TimeDate replaceObjectAtIndex:([index integerValue]) withObject: str];
[self.navigationController popViewControllerAnimated:YES];
}

I guess that your problem will be on NSDateFormatter since you have added seconds in it it will return the seconds too. hence there will be seconds delay.
Change your NSDateFormatter to
#"dd-MM-YYYY HH:mm"
Explanation:
LocalNotification will be set to the format #"dd-MM-YYYY HH:mm:SS" so we haveto convert it to the format #"dd-MM-YYYY HH:mm" (Without seconds).

Related

Is it possible to have two local notification in app

I wanted to have two local notification ,both have different time ,let say my first notification will give alert after 1 minute and the second will give alert after 2 minutes.
I have tried it to create two in appDelegate but only first one is giving me the notification and not the second one .
How can I achieve this ?
Yes It is Possible to set two LocalNotification in any iOS Application
See below method by which you can set multiple LocalNotifications
You just Need to pass required parameter to this method.
- (void)setAlarmFor:(NSArray*)datesArray forTime:(NSString*)atTime notificationName:(NSString*)name
{
for(int dayIndex=0;dayIndex <[datesArray count];dayIndex++)
{
Class cls = NSClassFromString(#"UILocalNotification");//
if (cls != nil) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
NSString* dateStr=[datesArray objectAtIndex:dayIndex];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *tempDate = [dateFormatter dateFromString:dateStr];
NSString *tempString = [dateFormatter stringFromDate:tempDate];
tempString = [NSString stringWithFormat:#"%# %#",tempString,atTime];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSDate *firetAtThisDate = [dateFormatter dateFromString:tempString];
UILocalNotification *localNotif = [[cls alloc] init];
localNotif.fireDate =firetAtThisDate;//here set the Date at which mnotification fire;
NSLog(#"Notification date is:%#",firetAtThisDate);
localNotif.alertBody =name;
localNotif.alertAction = #"Your'Alert message";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
NSDictionary *userDict = [NSDictionary dictionaryWithObject:tempString
forKey:tempString];//by using this we can further cancel the Notification
localNotif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[dateFormatter release];
}
}
}
And In Appdelegate Class Prepare Action what you want as Notification Fire
//This Below Line will goes to the Appdelegate DidFinishLaunching Method
Class cls = NSClassFromString(#"UILocalNotification");
if (cls)
{
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification)
{
//do what you want
}
}
application.applicationIconBadgeNumber = 0;
//End of Appdelegate DidFinishLaunching Method.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
//do what you want
}
sure , you use one or more local notifications in your app. try this code in your project
-(void) setLocalNotification
{
NSTimeInterval todayTimeIntervel=[[NSDate date]timeIntervalSince1970];
NSTimeInterval nextOneMinTimeIntervel;
nextOneMinTimeIntervel = todayTimeIntervel + 60 ;
NSTimeInterval nexttwoMinTimeIntervel;
nexttwoMinTimeIntervel = todayTimeIntervel + 60*3;
NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:nextOneMinTimeIntervel];
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:nexttwoMinTimeIntervel];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSString *strDate1 = [dateFormat stringFromDate:date1];
NSString *strDate2 = [dateFormat stringFromDate:date2];
NSArray *arr = [NSArray arrayWithObjects:strDate1,strDate2, nil];
NSArray *titleArr = [NSArray arrayWithObjects:#"First LocalNotification",#"Second LocalNotification", nil];
for (int i =0; i < 2; i++)
{
NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithObjectsAndKeys:[arr objectAtIndex:i],#"dateStr",[titleArr objectAtIndex:i],#"title", nil];
[self scheduleLocalNotification:dic];
}
}
-(void) scheduleLocalNotification:(NSMutableDictionary*) dic
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSLog(#"%#", [dateFormat dateFromString:[dic objectForKey:#"dateStr"]]);
localNotif.fireDate = [dateFormat dateFromString:[dic objectForKey:#"dateStr"]];
localNotif.timeZone = [NSTimeZone systemTimeZone];
localNotif.alertAction = #"View";
localNotif.alertBody = [dic objectForKey:#"title"];
localNotif.userInfo = dic;
NSLog(#"value of infoDic %#",dic);
localNotif.repeatInterval = NSDayCalendarUnit;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
// get app instance
UIApplication *app = [UIApplication sharedApplication];
// create local notif
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
if (notification) {
NSDate *oneMinuteFromNow = [[NSDate date] dateByAddingTimeInterval:60];
notification.fireDate = oneMinuteFromNow;
notification.timeZone = [NSTimeZone defaultTimeZone];
NSString *notificationMessage = #"First";
notification.alertBody = notificationMessage;
notification.soundName = UILocalNotificationDefaultSoundName;
// schedule notification
[app scheduleLocalNotification:notification];
// fire notification right away
[app presentLocalNotificationNow:notification];
}
UILocalNotification *notification1 = [[[UILocalNotification alloc] init] autorelease];
if (notification1) {
NSDate *oneMinuteFromNow1 = [[NSDate date] dateByAddingTimeInterval:120];
notification1.fireDate = oneMinuteFromNow1;
notification1.timeZone = [NSTimeZone defaultTimeZone];
NSString *notificationMessage1 = #"Second";
notification1.alertBody = notificationMessage1;
notification1.soundName = UILocalNotificationDefaultSoundName;
// schedule notification
[app scheduleLocalNotification:notification1];
// fire notification right away
[app presentLocalNotificationNow:notification1];
}
By writing this you ll get one notification after 1min and second one after 2 min. In "didReceiveLocalNotification" method you can check the notification type and can show alert msg.
Hope this will help you.
Yes you can use the multiple local notification in your application.
Check this link.
Hope it helpfull for you

Manage Multiple UILocal Notification

I have created multiple UI local Notifications , say 100. I have an array of UILocalNotifications which are scheduled as:
-(void) scheduleNotification{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[self.notifications removeAllObjects];
for (int i = 0; i< [delegate.viewController.contactList count] ; i++) {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSString *name = [[delegate.viewController.contactList objectAtIndex:i]objectForKey:NAME_KEY];
NSString *birthday = [[delegate.viewController.contactList objectAtIndex:i]objectForKey:BIRTHDAY_KEY];
if (birthday) {
[formatter setDateFormat:#"MM/dd/yyyy"];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date = [formatter dateFromString:birthday];
if (date == nil) {
[formatter setDateFormat:#"MM/dd"];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
date = [formatter dateFromString:birthday];
}
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
componentsEnd.year = [[NSDate date] year];
date = [gregorianEnd dateFromComponents:componentsEnd];
self.alarmTime = [date dateByAddingTimeInterval:self.mTimeInterval];
localNotification.fireDate = _alarmTime;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = 1;
NSString *itemName = #"B'day Alert!!!";
NSString *msgName = [NSString stringWithFormat:#"Celebrate %#'s B'day",name];
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:itemName,MessageKey, msgName,TitleKey, nil];
localNotification.userInfo = userDict;
localNotification.soundName = self.soundName;
localNotification.alertBody = [NSString stringWithFormat:#"Celebrate %#'s B'day",name];
[self.notifications addObject:localNotification];
}
}
}
}
I have implemented my applicationDidEnterBackground delegate as:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification* notification;
for (int i = 0; i< [self.settingVC.notifications count]; i++) {
notification = [self.settingVC.notifications objectAtIndex:i];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
Also, in didReceiveLocalNotification delegate I have this:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
NSString *itemName = [notification.userInfo objectForKey:TitleKey];
NSString *messageTitle = [notification.userInfo objectForKey:MessageKey];
[self _showAlert:itemName withTitle:messageTitle];
application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}
But the problem is that i'm not getting desired output.Any help would be appreciated. I know that at an application can have only a limited number of scheduled notifications; the system keeps the soonest-firing 64 notifications and discards the rest. So, how I will handle those 100 or more UILocalNotification?

NSNotification before 2 days from targeted date

I want to fire a notification before 2 days from targeted date.Currently I am using below code to fire notification but there how to fire notification exactly before 2 days from targeted date.
NSString *frstdate = [[calenderarray objectAtIndex:k] objectForKey:#"date"];
NSLog(#"frstdate..%#",frstdate);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:frstdate];
NSLog(#"date..%#",date);
NSDate *dateToFire = [[[NSDate alloc] initWithTimeInterval:-24*60*60 sinceDate:date]autorelease];
NSLog(#"dateToFire..%#",dateToFire);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
localNotif.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"Get Food"], #"foodItem", nil] ;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
Thanks in advance.
You should use NSCalendar and NSDateComponents to do the maths - something like:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* twoDaysAgo = [[NSDateComponents alloc] init];
twoDaysAgo.day = -2;
NSDate* dateToFire = [calendar dateByAddingComponents:twoDaysAgo toDate:date options:0];
You can do arithmetic with calendar dates (year/month/day/hour... representation in a given timezone) via the NSCalendar class. Although in most cases, "24*60*60" seconds will be one day -- users probably won't notice the difference.

scheduleLocalNotification doesn´t work

when I get the time/date from dateTimePicker.date, the Notification work, but when I fire the date with dateFromString, the notification doesn´t work.
The Code:
-(IBAction)alarmSetButtonTapped:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale systemLocale];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
NSString *tmp = #"2012-09-05 10:19";
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *dateFromString = [dateFormatter dateFromString: tmp];
NSLog(#"Alarm TMP %#", dateFromString);
[dateFormatter release];
[self scheduleLocalNotificationWithDate:dateFromString];
[self presentMessage:#"Alarm set"];
};
Please can you help me??
EDIT:
-(void) scheduleLocalNotificationWithDate:(NSDate *)fireDate {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = fireDate;
notification.alertBody = #"Time to wake up";
notification.soundName = #"clock.mp3";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[notification release];
}
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// Set the fire date/time
[localNotification setFireDate:yourDate];
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
localNotification.applicationIconBadgeNumber=1;
// Setup alert notification
[localNotification setAlertAction:#"Open App"];
[localNotification setAlertBody:[randonQuotesDic objectForKey:#"Rajneesh"]];
[localNotification setAlertBody:#"You had set a Local Notification on this time"];
localNotification.soundName=UILocalNotificationDefaultSoundName;
[localNotification setHasAction:YES];
UIApplication *app=[UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];

How to send the same alarmid when multiple days are set for a single alarm in iPhone?

I have set the alarm with notification for multiple days i.e. when I set a particular alarm for every Monday, Tuesday, Wednesday that particular alarm should show notification on every Monday, Tuesday and Wednesday. This is working fine. When I am setting an alarm for multiple days I am creating a timestamp and saving it in userinfo of notification.
So my problem is when for a particular it gets a day; Monday it creates a new alarmid and save it in the userinfo, and when it gets Tuesday it creates a new alarmid and saves in the userinfo object. Finally with Wednesday, I want that when I set a particular alarm for multiple days using the notification object it should create only one alarmid for Monday, Tuesday and Wednesday not different alarmids.
This is my code:
-(void)scheduleNotification
{
itemDate = [[NSDate alloc] init];
timepicker = [[TTimePickerController alloc]init];
double double_date = (double)[[NSDate date] timeIntervalSince1970];
NSDate *now= [NSDate dateWithTimeIntervalSince1970:double_date];
selectedWeek = [[NSUserDefaults standardUserDefaults]arrayForKey:#"week"];
NSMutableArray *array = [[NSUserDefaults standardUserDefaults]objectForKey:#"time"];
NSInteger repeatCount = 7;
today = [NSDate date];
NSString *Stringdate;
calendar = [NSCalendar currentCalendar];
NSDateFormatter *format = [[[NSDateFormatter alloc]init]autorelease];
format.dateFormat = #"yyyy-MM-dd hh:mm";
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
dateFormat.dateFormat = #"yyyy-MM-dd";
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc]init]autorelease];
timeFormat.dateFormat = #"hh:mm";
for (NSDate *date in array)
{
if ([date isEqualToDate:now])
{
itemDate = date;
NSLog(#"%#",itemDate);
}
else if([date earlierDate:now]){
itemDate = date;
}
else if([date laterDate:now])
{
itemDate =date;
}
}
app.newtest = [[NSMutableDictionary alloc]init];
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
for (NSInteger i = 0; i < repeatCount; i++) {
date1 = [today dateByAddingTimeInterval:i * 24 * 60 * 60];
dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:date1];
if ([selectedWeek containsObject:[NSNumber numberWithInteger:dateComponents.weekday - 1]]) {
NSLog(#"weekday:%d",dateComponents.weekday);
// Adding the local notification.
Stringdate = [NSString stringWithFormat:#"%# %#",
[dateFormat stringFromDate:date1],
[timeFormat stringFromDate:itemDate]];
if ([today compare:[format dateFromString:Stringdate]] == NSOrderedAscending) {
notification.fireDate = [format dateFromString:Stringdate];
notification.timeZone = [NSTimeZone localTimeZone];
notification.alertBody = [NSString stringWithFormat:#"Notify:%#", Stringdate];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertAction = #"Open";
//Here i am creating the alarmid
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
NSNumber *timeStampObj = [NSNumber numberWithInt:timeStamp];
NSLog(#"%d",timeStampObj);
am.AlarmID =(int)timeStampObj;
NSLog(#"%#",am.AlarmID);
app = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
[app.newtest setObject:[NSNumber numberWithInteger:am.AlarmID]forKey:#"idtemp"];
[app.newtest setObject:app.timerdate forKey:#"iddate"];
notification.userInfo = app.newtest;
NSLog(#"notif userinfo:%#",notification.userInfo);
//NSLog(#"notif userinfo:%#",notification.userInfo);
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
}
}