Manage Multiple UILocal Notification - iphone

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?

Related

My remainder IPhone application getting delayed in seconds

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).

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

Local Notification Issue?

I am new in iPhone application development. I am doing alarm application. In this application I am using local notification. I am calling notification method in done button action. Now I clicked done button means notification fired correctly. Then again clicked mean also fired, again and again press means working wrongly, but I am used notification fire date time same time. In this time completed means again user click done button means again triggered notification.
I want to fire that particular time. Can you please help me.
Here I am using this source code.
-(IBAction)doneButton
{
[self scheduledNotification];
}
-(void)scheduledNotification
{
Resource *resourceLoader = [[Resource alloc] init];
NSDictionary *prefDic = [resourceLoader getPlistDataAsDictionary:#"preference"];
if ([#"ON" isEqualToString:[prefDic objectForKey:#"alarm"]])
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
NSString *musicName;
//NSDate *selectedDateTime = [[NSDate alloc]init];
selectedDateTime = [prefDic objectForKey:#"alarmtime"];
NSLog(#"saravanan periyasamy %#", selectedDateTime);
musicName = [NSString stringWithFormat:#"%#%#",[prefDic objectForKey:#"alarmmusic"],#".wav" ];
NSLog(#"musicname %#", musicName);
NSLog(#"saravanan periyasamy123 %#", selectedDateTime);
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = selectedDateTime; /* time for fireDate*/
NSLog(#"selectedtime %#",selectedDateTime);
notif.timeZone = [NSTimeZone systemTimeZone];
notif.alertBody = #"Alarm";
notif.alertAction = #"Show me";
notif.repeatInterval = 0;
notif.soundName = musicName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"saravanan"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
Class cls = NSClassFromString(#"UILocalNotification");
if (cls) {
UILocalNotification *notification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
//[self.viewController showReminder:reminderText];
[self.settingViewController showReminder1:reminderText];
}
}
application.applicationIconBadgeNumber = 0;
return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
//[self.viewController showReminder:reminderText];
[self.settingViewController showReminder1:reminderText];
}
hi i not understand what your question but here i post my one example code for LocalNotification just compare it or use this example....
here when user click done button then call "btnGo_Clicked" method
-(IBAction)btnGo_Clicked:(id)sender{
NSLog(#"\n ----------->>Go Clicked");
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSQuarterCalendarUnit fromDate:[exdatePicker date]];
[dc setDay:dc.day - 1];
NSDate *noticeDate = [[NSCalendar currentCalendar] dateFromComponents:dc];
NSDateFormatter* dateFormatterstring = [[NSDateFormatter alloc] init];
[dateFormatterstring setDateFormat:#"dd-MM-yyyy hh:mm:ss a"];
NSString *dateString = [dateFormatterstring stringFromDate:noticeDate];
txtExpirayDate.text = dateString;
UILocalNotification *notification = [[cls alloc] init];
notification.fireDate = noticeDate;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = [NSString stringWithFormat:#"%# your Licence Expiry Date is Tommorow",txtLicence.text];
notification.alertAction = #"Show me";
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:txtLicence.text forKey:kRemindMeNotificationDataKey];
notification.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[notification release];
}
exdatePicker.hidden=YES;
}
do some changes and you got your output
i hope this answer help you...
:)
Remove this line if you want multiple press on button.
[[UIApplication sharedApplication] cancelAllLocalNotifications];
because its removing your all previous notifications.

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];
}
}
}
}

how to check each and every object of array in the userdefaults

i am saving selected date from picker in array in userdefaults. So when i select a particular date and click on save that particular date is getting saved in userdefaults.This is done properly.But now i have problem.I need to compare each and every date and time of userdefaults with the current time .If an object gets equivalent to the current date and time then the notification should be shown.How is this possible.Thanks. This is my code
Here i am selecting my date through date picker and saving date in userdefaults.
this is my timepickercontroller.m
- (void)viewDidLoad {
time = [[NSString alloc] init];
CGRect pickerFrame = CGRectMake(0,40,0,0);
datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
datePicker.datePickerMode = UIDatePickerModeTime;
datePicker.date = [NSDate date];
[datePicker addTarget:self action:#selector(convertDueDateFormat) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[datePicker release];
}
-(void)convertDueDateFormat{
app = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
app.timerdate = [self.datePicker date];
NSLog(#"picker date:%#",selecteddate);
if ([[NSUserDefaults standardUserDefaults] valueForKey:#"time"]==nil)
{
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"time"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"time"]);
}
else
{
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:#"time"];
NSMutableArray *array_dates = [[NSMutableArray alloc] init];
for(int i =0;i<[array count];i++)
{
[array_dates addObject:[array objectAtIndex:i]];
}
[array_dates addObject:app.timerdate];
[[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:#"time"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"time"]);
}
}
this is the controller where i am setting notification
-(IBAction)save{
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate *currentime = [NSDate date];
currentcheck = [NSString stringWithFormat:#"%#",[dateFormatter stringFromDate:currentime] ];
NSLog(#"currenttime:%#",currentcheck);
timepicker = [[TTimePickerController alloc]init];
if (app.timerdate == NULL && interval == NULL && newsound == NULL)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Set Date,interval,sound for alarm" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
else
{
[self scheduleNotification];
[self saveInDatabase];
}
}
-(void)scheduleNotification
{
[[UIApplication sharedApplication]cancelAllLocalNotifications];
timepicker = [[TTimePickerController alloc]init];
NSDate *newtestdate = [[NSUserDefaults standardUserDefaults]objectForKey:#"time"];
NSLog(#"fireDate=%#", newtestdate);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:newtestdate];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:newtestdate];
NSDateComponents *dateComps = [[NSDateComponents alloc]init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls!= nil) {
UILocalNotification *notif = [[cls alloc]init];
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];
}
}
Supposing ur time format is like this hh:mm:ss
NSDate *currentTime=[NSDate date];
NSArray *timeArray=[[NSUserDefaults standardUserDefaults]objectForKey:#"time"];
NSDateFormatter* tempFormat = [[[NSDateFormatter alloc]init]autorelease];
[tempFormat setDateFormat:#"h:mm a"];
NSString* tempStr = [NSString stringWithFormat:#"%#",[tempFormat stringFromDate:date]];
if([tempStr isEqualToString:[NSString stringWithFormat:#"%#",[timeArray objectAtIndex:0]]]){
//Make any decision
//Similarly compare all the time in the array by changing the index using for-loop.
}
I suspect that what you really want to do is not to compare the dates, but to set the fire date of the notification to the date you got from the array.
To do that, you enumerate the array and launch an NSNotification for each timerDate:
NSArray *timerDates = [NSUser Defaults standardUserDefaults] objectforKey:#"time"];
NSDate *now = [NSDate date];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
// .... general setup of all notifs here.
for (NSDate * aDate in timerDates) {
localNotif.fireDate = aDate;
//... further setup of each individual notif here....
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
[localNotif release];
However, from your code, it looks like you're getting a single date from defaults:
NSDate *newtestdate = [[NSUserDefaults standardUserDefaults]objectForKey:#"time"];
but you save an array there in the method
-(void)convertDueDateFormat{
...
[[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:#"time"];
So which one is it?
If you have an array, you can test its values as dates:
NSArray *timerDates = [NSUser Defaults standardUserDefaults] objectforKey:#"time"];
NSDate *now = [NSDate date];
_block int timerIndex; // can be changed inside the block
// use a block to enumerate the array
[timerDates enumerateObjectsUsingBlock:^(id obj,NSUInteger index, BOOL *stop){
if(fabs([(NSDate *)obj timeIntervalSinceDate:now])< 1.0) {
*stop=YES;
timerIndex = index;
}
} ];
Then use timerIndex to get the right date:
localNotif.firedate = [timerDates objectAtIndex:timerIndex];
Definitely also look at the documentation for comparing dates (Apple class documentation for NSDate is good). This is just one way to do it, and probably not the best.
(sorry about my formatting. I'm kinda new at this)