I have made an app which is an Customized Alarm App. The UILocalNotification should invoke at the time selected by me in UIDatePicker, but is is not invoking at correct timing. For example, I selected the time as 2:00PM for the alarm, so the notification will invoke between 2:00PM and 2:01PM... but not sure when... it is giving me a delay of random time. In my UITableView you can see that it is the description displayed is also comes wrong. I know I am from India so it showing GMT timings, but can it could be corrected?
Here is my whole code:-
-----------------------------AppDelegate.m File :------------------------------
#synthesize window,viewController,timeViewController;
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
int x = [[NSUserDefaults standardUserDefaults] integerForKey:#"Mayank"];
if( x == 1 )
{
timeViewController = [[TimeViewController alloc]initWithNibName:#"TimeViewController" bundle:nil];
timeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = timeViewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
timeViewController.view.frame = frame;
[self.window addSubview:timeViewController.view];
}
else
{
[[NSUserDefaults standardUserDefaults]setInteger:1 forKey:#"Mayank"];
[[NSUserDefaults standardUserDefaults]synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Do you want to set the Default Alarm?" message:#"at 4:20 PM" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
[alert release];
}
sleep(1);
[self.window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotification =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
NSString *reminderText = [localNotification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
}
return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
timeViewController = [[TimeViewController alloc]initWithNibName:#"TimeViewController" bundle:nil];
timeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = timeViewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
timeViewController.view.frame = frame;
[self.window addSubview:timeViewController.view];
}
if(buttonIndex == 1)
{
viewController = [[SetAlarmViewController alloc]initWithNibName:#"SetAlarmViewController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = viewController.view.frame;
frame.origin = CGPointMake(frame.origin.x,frame.origin.y + statusBarFrame.size.height );
viewController.view.frame = frame;
[self.window addSubview:viewController.view];
}
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
application.applicationIconBadgeNumber = 0;
}
-----------------------------mainViewController.m File :------------------------------
#implementation SetAlarmViewController
#synthesize datePicker,tableview, eventText,titleBar,setAlarmButton,returnKeyType;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (The420DudeAppDelegate *)[[UIApplication sharedApplication] delegate];
eventText.returnKeyType = UIReturnKeyDone;
// datePicker.minimumDate = [NSDate date];
NSDate *now = [NSDate date];
[datePicker setDate:now animated:YES];
eventText.delegate = self;
index = 0;
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
[self.tableview reloadData];
}
- (IBAction) scheduleAlarm:(id) sender {
[eventText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = pickerDate;
// NSLog(#"%#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// NSLog(#"%#",localNotif.timeZone);
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"Show me";
localNotif.repeatInterval = NSDayCalendarUnit;
localNotif.soundName = #"jet.wav";
// Specify custom data for the notification
NSDictionary *userDict = [NSDictionary dictionaryWithObject:eventText.text
forKey:kRemindMeNotificationDataKey];
localNotif.userInfo = userDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
[self.tableview reloadData];
eventText.text = #"";
viewController = [[TimeViewController alloc] initWithNibName:#"TimeViewController" bundle:nil];
[self presentModalViewController:viewController animated:YES];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
index = indexPath.row;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning!!!"
message:#"Are you sure you want to Delete???" delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok",nil];
[alertView show];
[alertView release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notify = [notificationArray objectAtIndex:index];
if(buttonIndex == 0)
{
// Do Nothing on Tapping Cancel...
}
if(buttonIndex ==1)
{
if(notify)
[[UIApplication sharedApplication] cancelLocalNotification:notify];
}
[self.tableview reloadData];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
- (void)showReminder:(NSString *)text {
/*
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:#"hello" delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self.tableview reloadData];
[alertView release];
*/
NSString *path = [[NSBundle mainBundle]pathForResource:#"jet" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
player.numberOfLoops = -1;
[player play];
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
[actionSheet showInView:self.view];
// [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
[player stop];
if(buttonIndex == 0)
{
NSLog(#"OK Tapped");
}
if(buttonIndex == 1)
{
NSLog(#"Cancel Tapped");
}
}
This Pic Shows My App View :
NSDate *pickerDate = [self.pickerTime date];
// 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]];
[dateComps setMinute:[timeComponents minute]];
**[dateComps setSecond:00];**
NSDate *itemDate = [calendar dateFromComponents:dateComps];
localNotification.fireDate = itemDate;
just keep in mind, the date from datepicker comes aligned with GMT. you have to convert to your own timezone by yourself. this could be the issue in your case.
I think the problem here has to do with the NSDatePicker returning the seconds of the current time along with the selected time. You need to strip the seconds from the date returned by the NSDatePicker and use that for your alarm and local notification.
NSDate *selectedDate = [datePicker date]; // you don't need to alloc-init the variable first
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *dc = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:selectedDate];
selectedDate = [cal dateFromComponents:dc];
// now you have an NSDate with zero seconds for your alarm
You should get much better accuracy on your notifications, but I don't think they're guaranteed to be exactly on the split second.
Related
IPhone: I am doing my remainder app in Iphone,While i navigate from my "create new"-view to "edit"-View, I need my DatePicker to display the Value i have stored already when i just created the remainder, HENCE I need the DatePicker to return the time/date i specified when it is in edit view -Pls Help
1.My RemainderSetUpViewcontroller.h
`
#protocol RemainderDelegate <NSObject>
-(void)store:(NSArray *) remainderDel:(NSArray *) TimeDateDel;
#end
#interface RemainderSetUpViewcontroller : UIViewController<UITextFieldDelegate,UITextFieldDelegate>
{
UITextField *textField1;
NSString *str;
UIDatePicker *datePicker;
NSDate *date;
NSMutableArray *remainder;
NSMutableArray *TimeDate;
UILocalNotification* notification;
}
#property (strong, nonatomic)IBOutlet NSString* remainderr;
#property (strong, nonatomic)IBOutlet NSString *index;
#property(strong, nonatomic) id <RemainderDelegate> delegate;
-(void)addRemainder;
-(void)actionDone;
#end
`
2My RemainderSetUpViewcontroller.m:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addRemainder)];
self.navigationItem.rightBarButtonItem=add;
//TextField1...............................................................................................................
self.title=#"Add Remainder";
textField1 = [[UITextField alloc]initWithFrame:CGRectMake(20, 60, 280, 34)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField1.delegate = self;
textField1.placeholder = #"Enter the Reminder name";
[self.view addSubview:textField1];
//datePicker&TextField2....................................................................................................
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,210, self.view.frame.size.width, self.view.frame.size.height)];
[datePicker addTarget:self action:#selector(actionDone) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
//UserDefaults.............................................................................................................
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
remainder = [[NSMutableArray alloc]init];
TimeDate = [[NSMutableArray alloc]init];
if ([ud objectForKey:#"remainder"])
{
remainder = [[ud objectForKey:#"remainder"]mutableCopy];
TimeDate = [[ud objectForKey:#"TimeDate"]mutableCopy];
}
//to make the fields visible when we try to edit it............................................................................
if ([remainderr isEqualToString:#"edit"])
{
self.title = #"Reminder Edit";
textField1.text = [remainder objectAtIndex:[index integerValue]];
str = [TimeDate objectAtIndex:[index integerValue]];
}
}
#pragma mark - doneClicked
//DoneButton.................................................................................................................
-(void)actionDone
{
date = datePicker.date;
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
[datePicker setDate:[NSDate date]];
dateform.dateFormat = #"dd-MM-YYYY HH:mm:SS";
str=[dateform stringFromDate:date];
}
#pragma mark - AddRemainder Notifications
//addButton.................................................................................................................
-(void)addRemainder
{
//LocalNotification.........................................................................................................
notification = [[UILocalNotification alloc] init];
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([remainderr isEqualToString:#"edit"])
{
[remainder replaceObjectAtIndex:[index integerValue] withObject:textField1.text];
[TimeDate replaceObjectAtIndex:[index integerValue] withObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else if([remainderr isEqualToString:#"delete"])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
else
{
if((textField1.text!=NULL)&&( date!=NULL))
{
[remainder addObject:textField1.text];
[TimeDate addObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert !" message:#"Please Give a title for your Remainder " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
}
}
//Adding objects............................................................................................................
//NSLog(#"%# %#", remainder, TimeDate);
[self.delegate store:remainder :TimeDate];
NSLog(#"The notifications is \n %#",notification);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
`
Thank you.
To display saved date in DatePicker, You need to set saved date in datepicker.
[datePicker setDate:savedDate animated:NO];
To display saved date in DatePicker, You need to set saved date in datepicker.
[datePicker setDate:savedDate animated:NO];
to get Date from datePicker
NSDate *date = datePicker.date;
In default While I create a UIDate picker in my remainder app, when i click done, the current time has to be entered in default or if the date picker is animated the date value can change but in my case the current time is not returned in default ! Please help, 1.My RemainderSetUpViewcontroller.h
`
#protocol RemainderDelegate <NSObject>
-(void)store:(NSArray *) remainderDel:(NSArray *) TimeDateDel;
#end
#interface RemainderSetUpViewcontroller : UIViewController<UITextFieldDelegate,UITextFieldDelegate>
{
UITextField *textField1;
NSString *str;
UIDatePicker *datePicker;
NSDate *date;
NSMutableArray *remainder;
NSMutableArray *TimeDate;
UILocalNotification* notification;
}
#property (strong, nonatomic)IBOutlet NSString* remainderr;
#property (strong, nonatomic)IBOutlet NSString *index;
#property(strong, nonatomic) id <RemainderDelegate> delegate;
-(void)addRemainder;
-(void)actionDone;
#end
`
2My RemainderSetUpViewcontroller.m:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addRemainder)];
self.navigationItem.rightBarButtonItem=add;
//TextField1...............................................................................................................
self.title=#"Add Remainder";
textField1 = [[UITextField alloc]initWithFrame:CGRectMake(20, 60, 280, 34)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField1.delegate = self;
textField1.placeholder = #"Enter the Reminder name";
[self.view addSubview:textField1];
//datePicker&TextField2....................................................................................................
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,210, self.view.frame.size.width, self.view.frame.size.height)];
[datePicker addTarget:self action:#selector(actionDone) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
//UserDefaults.............................................................................................................
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
remainder = [[NSMutableArray alloc]init];
TimeDate = [[NSMutableArray alloc]init];
if ([ud objectForKey:#"remainder"])
{
remainder = [[ud objectForKey:#"remainder"]mutableCopy];
TimeDate = [[ud objectForKey:#"TimeDate"]mutableCopy];
}
//to make the fields visible when we try to edit it............................................................................
if ([remainderr isEqualToString:#"edit"])
{
self.title = #"Reminder Edit";
textField1.text = [remainder objectAtIndex:[index integerValue]];
str = [TimeDate objectAtIndex:[index integerValue]];
}
}
#pragma mark - doneClicked
//DoneButton.................................................................................................................
-(void)actionDone
{
date = datePicker.date;
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
[datePicker setDate:[NSDate date]];
dateform.dateFormat = #"dd-MM-YYYY HH:mm:SS";
str=[dateform stringFromDate:date];
}
#pragma mark - AddRemainder Notifications
//addButton.................................................................................................................
-(void)addRemainder
{
//LocalNotification.........................................................................................................
notification = [[UILocalNotification alloc] init];
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([remainderr isEqualToString:#"edit"])
{
[remainder replaceObjectAtIndex:[index integerValue] withObject:textField1.text];
[TimeDate replaceObjectAtIndex:[index integerValue] withObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else if([remainderr isEqualToString:#"delete"])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
else
{
if((textField1.text!=NULL)&&( date!=NULL))
{
[remainder addObject:textField1.text];
[TimeDate addObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert !" message:#"Please Give a title for your Remainder " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
}
}
//Adding objects............................................................................................................
//NSLog(#"%# %#", remainder, TimeDate);
[self.delegate store:remainder :TimeDate];
NSLog(#"The notifications is \n %#",notification);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
`
Thank you.
Already a descusion carried about this please check the link. Delete a particular local notification
Just add one line after a line in your code
datePicker.datePickerMode = UIDatePickerModeDateAndTime;
Add Below line to your code and try
datePicker.date=[NSDate date];
In my Iphone app to create remainder, in the UIDate picker, the current time is not returned in default.Here my code is please help me.
MY viewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addRemainder)];
self.navigationItem.rightBarButtonItem=add;
//TextField1...............................................................................................................
self.title=#"Add Remainder";
textField1 = [[UITextField alloc]initWithFrame:CGRectMake(20, 60, 280, 34)];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField1.delegate = self;
textField1.placeholder = #"Enter the Reminder name";
[self.view addSubview:textField1];
//datePicker&TextField2....................................................................................................
datePicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0,210, self.view.frame.size.width, self.view.frame.size.height)];
[datePicker addTarget:self action:#selector(actionDone) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:datePicker];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
//UserDefaults.............................................................................................................
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
remainder = [[NSMutableArray alloc]init];
TimeDate = [[NSMutableArray alloc]init];
if ([ud objectForKey:#"remainder"])
{
remainder = [[ud objectForKey:#"remainder"]mutableCopy];
TimeDate = [[ud objectForKey:#"TimeDate"]mutableCopy];
}
//to make the fields visible when we try to edit it............................................................................
if ([remainderr isEqualToString:#"edit"])
{
self.title = #"Reminder Edit";
textField1.text = [remainder objectAtIndex:[index integerValue]];
str = [TimeDate objectAtIndex:[index integerValue]];
}
}
#pragma mark - doneClicked
//DoneButton.................................................................................................................
-(void)actionDone
{
date = datePicker.date;
NSDateFormatter *dateform=[[NSDateFormatter alloc]init];
[datePicker setDate:[NSDate date]];
dateform.dateFormat = #"dd-MM-YYYY HH:mm:SS";
str=[dateform stringFromDate:date];
}
#pragma mark - AddRemainder Notifications
//addButton.................................................................................................................
-(void)addRemainder
{
//LocalNotification.........................................................................................................
notification = [[UILocalNotification alloc] init];
notification.fireDate = date;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([remainderr isEqualToString:#"edit"])
{
[remainder replaceObjectAtIndex:[index integerValue] withObject:textField1.text];
[TimeDate replaceObjectAtIndex:[index integerValue] withObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else if([remainderr isEqualToString:#"delete"])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
else
{
if((textField1.text!=NULL)&&( date!=NULL))
{
[remainder addObject:textField1.text];
[TimeDate addObject: str];
[self.navigationController popViewControllerAnimated:YES];
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"Alert !" message:#"Please Give a title for your Remainder " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
}
}
//Adding objects............................................................................................................
//NSLog(#"%# %#", remainder, TimeDate);
[self.delegate store:remainder :TimeDate];
NSLog(#"The notifications is \n %#",notification);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
Thank you
Make your VoidAction as follows,
-(void)actionDone
{
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];
}
Note: Be relevant when you post questions. Thank you.
I have followed this tutorial
http://ios.biomsoft.com/2011/08/27/iphone-programming-tutorial-–-local-notifications/
I am able to run the app, however in order to run the app I have remove the following code in my appdelegate.m
You can see the error in the picture above.
Why do I receive the error and how do I fix the error?
Here is my code.
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {
IBOutlet UITableView *tableview;
IBOutlet UIDatePicker *datePicker;
IBOutlet UITextField *eventText;
}
#property (nonatomic, retain) IBOutlet UITableView *tableview;
#property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
#property (nonatomic, retain) IBOutlet UITextField *eventText;
- (IBAction) scheduleAlarm:(id) sender;
#end
.m
#implementation ViewController
#synthesize datePicker,tableview, eventText;
- (IBAction) scheduleAlarm:(id) sender {
[eventText resignFirstResponder];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// 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];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [eventText text];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue"
forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[self.tableview reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
datePicker = nil;
tableview = nil;
eventText = nil;
}
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// We only have one section
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of notifications
return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
// Get list of local notifications
NSArray *notificationArray = [[UIApplication sharedApplication]
scheduledLocalNotifications];
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
// Display notification info
[cell.textLabel setText:notif.alertBody];
[cell.detailTextLabel setText:[notif.fireDate description]];
return cell;
}
#end
You have to create an instance of the viewControllerfirst:
ViewController *viewController = [[ViewController alloc] init];
// set the frame, do other stuff..
[_window addSubview:viewController.view];
please check your AppDelegate code first
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
/******
YOUR CODE HERE
******/
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
Ok so after doing some playing around. I was able to get the app to run without having to change the app delegate at all.
Not sure why in the tutorial he states to do so.
Thanks for you help.
i have set an alarm through uilocalnotifications.so when my app is in background my local notification is displayed with 2 buttons close and view.when my app is in foreground it displays and alertview with 2 buttons ,stop and snooze.when the stop button is clicked i want that my alarm should stop and when snooze button is clicked i want that the notification should appear after 5 mins.How is this possible.Please help me in solving this prob.Thanks.
this is my code :
//this is my controller class where i am setting my notification
- (void)clearNotification {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (void)scheduleNotification {
[reminderText resignFirstResponder];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Did you forget something?";
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSInteger index = [scheduleControl selectedSegmentIndex];
switch (index) {
case 1:
notif.repeatInterval = NSMinuteCalendarUnit;
break;
case 2:
notif.repeatInterval = NSHourCalendarUnit;
break;
case 3:
notif.repeatInterval = NSDayCalendarUnit;
break;
case 4:
notif.repeatInterval = NSWeekCalendarUnit;
break;
default:
notif.repeatInterval = 0;
break;
}
NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -
- (void)showReminder:(NSString *)text {
if (reminderText != nil) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:text delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"stop",#"Snooze",nil];
[alertView show];
[alertView release];
}
}
//this is my appdelegate where i am receiving my notification
- (void)clearNotification {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (void)scheduleNotification {
[reminderText resignFirstResponder];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Did you forget something?";
notif.alertAction = #"Show me";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSInteger index = [scheduleControl selectedSegmentIndex];
switch (index) {
case 1:
notif.repeatInterval = NSMinuteCalendarUnit;
break;
case 2:
notif.repeatInterval = NSHourCalendarUnit;
break;
case 3:
notif.repeatInterval = NSDayCalendarUnit;
break;
case 4:
notif.repeatInterval = NSWeekCalendarUnit;
break;
default:
notif.repeatInterval = 0;
break;
}
NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
#pragma mark -
#pragma mark === Public Methods ===
#pragma mark -
- (void)showReminder:(NSString *)text {
if (reminderText != nil) {
/*newtest *new = [[newtest alloc]initWithNibName:#"newtest" bundle:nil];
[self.navigationController pushViewController:new animated:YES];
[new release];*/
// - (void)alertView:(UIAlertView *)alert
// didDismissWithButtonIndex:(NSInteger) buttonIndex
// {
// if (buttonIndex == 0)
// {
// NSLog(#"Cancel Tapped.");
// }
// else if (buttonIndex == 1)
// {
// NSLog(#"OK Tapped. Hello World!");
// }
// }
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Reminder"
message:text delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"stop",#"Snooze",nil];
[alertView show];
[alertView release];
}
}
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if(buttonIndex == 0)
{
NSLog(#"Button 1 was selected.");
}
else if([title isEqualToString:#"Button 2"])
{
NSLog(#"Button 2 was selected.");
}
}
//this is my appdelegate where i am receiving notification
NSString *kRemindMeNotificationDataKey = #"kRemindMeNotificationDataKey";
#pragma mark -
#pragma mark === Application Delegate Methods ===
#pragma mark -
- (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];
[viewController showReminder:reminderText];
/*newtest *new = [[newtest alloc]initWithNibName:#"newtest" bundle:nil];
[window addSubview:new.view];*/
}
}
application.applicationIconBadgeNumber = 0;
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
// UIApplicationState state = [application applicationState];
// if (state == UIApplicationStateInactive) {
// Application was in the background when notification
// was delivered.
// }
application.applicationIconBadgeNumber = 0;
NSString *reminderText = [notification.userInfo
objectForKey:kRemindMeNotificationDataKey];
[viewController showReminder:reminderText];
NSLog(#"Recieved Notification %#",notification);
}
When you click your snooze button you set another local notification. When you click in snooze button you call another function. In this you take current time and in fire date you set it with adding 5 minutes.
When your notification is coming then u take one alert in received notification delegate method and the button click of alert u call this function
Click on your snooze alert click u call this function.
-(void)addNewNotification{
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody =#"HI"
localNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:5*60];
localNotification.timeZone = [NSTimeZone localTimeZone];
localNotification.applicationIconBadgeNumber = localNotification.applicationIconBadgeNumber+1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
NSLog(#"%#",[[UIApplication sharedApplication] scheduledLocalNotifications]);
}
I think you should use the alertview delegate method,clickedAtIndex.
Then check if the index is what you want say 1 for snooze,then make it repeat after the 5 minutes.
Thanks