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
Related
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.
In my app i am getting data using some network connection
i want to show that data in notification bar (status bar) in iPhone
so how to add data that i can see in status bar of iPhone when i drag it down
i search many tutorials but i did not find any good one please help me
Please tell me some ideas that i can manage my data in notification or any good tutorial
Please suggest any good tutorial so i can manage my dynamic data in notification bar
Thanks
After getting data:
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = date; // date after 10 sec from now
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = text; // text of you that you have fetched
// 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];
To handle onclick of Noification:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(#"Recieved Notification %#",localNotif);
}
return YES;
}
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
// Handle the notificaton when the app is running
NSLog(#"Recieved Notification %#",notif);
}
i think, uilocalnotificatios are deprecated. now you can use, UNUserNotificationCenter. we can add image to it as well as shown below:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;
[center requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
//NSLog(#"Something went wrong");
}
}];
int dayCounter =5;
int minute = 48;
{
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = dayCounter;
dayCounter++;
components.hour = 12;
components.minute = minute;
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:#"Notification!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:#"We made a surprise Edit for You" arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
objNotificationContent.badge = #([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
UNNotificationAttachment *attachment = nil;
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:filePath];
NSError *attachmentError = nil;
attachment = [UNNotificationAttachment attachmentWithIdentifier:#"image"
URL: outputURL
options:nil
error:&attachmentError];
if (attachmentError) {
return;
}
objNotificationContent.attachments=#[attachment];
NSString *identifier = #"UYLLocalNotification";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:objNotificationContent trigger: trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
else
{
}
}];
Issue is, i put a date picker programmatically. In date picker i just used to display time from 1mins to 23 hours. User is supposed to set the time in the picker, and set up the notification.
Now,i get notification in background but only one time.I have to repeat time until timer will not stop.
I found too many links and source but not able to solve this issue
My Code:
In Appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
application.applicationIconBadgeNumber = 0;
//------ Handle launching from a notification-------
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
self.localNotification =[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (self.localNotification)
{
application.applicationIconBadgeNumber = self.localNotification.applicationIconBadgeNumber-1;
NSLog(#"badge number: %d", application.applicationIconBadgeNumber);
[self playSoundWithNotification:self.localNotification];
}
else
{
[[UIApplication sharedApplication]cancelAllLocalNotifications];
}
}
didenterinbackground:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(#"Application entered background state.");
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];
dispatch_async(dispatch_get_main_queue(), ^{
while ([application backgroundTimeRemaining] > 1.0)
{
NSString *str_friend = #"Hello,";
if (str_friend)
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif)
{
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(#"%# has a message for you.", nil), str_friend];
localNotif.alertAction = NSLocalizedString(#"Read Msg", nil);
localNotif.soundName = #"alarmsound.caf";
//localNotif.soundName =[NSString stringWithFormat:#"%#.mp3",str_Alarm];
localNotif.applicationIconBadgeNumber = 1;
[application presentLocalNotificationNow:localNotif];
NSLog(#"sound: %#, alertAction: %#, alerBody: %#",localNotif.soundName, localNotif.alertAction, localNotif.alertBody);
str_friend = nil;
break;
}
}
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}
-
(void)playSoundWithNotification:(UILocalNotification *)notification
{
notification.soundName=[NSString stringWithFormat:#"%#.mp3",str_Alarm];
NSLog(#"soundname: %#",notification.soundName);
}
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{
testDate=notif.fireDate;
NSLog(#"DATE IS: %#, %#",testDate, notif.fireDate);
// Handle the notificaton when the app is running
NSLog(#"Recieved Notification %#",notif);
[self playSoundWithNotification:notif];
[self _showAlert:[NSString stringWithFormat:#"%#",str_Motivation] withTitle:#"Daily Achiever"];
}
- (void) _showAlert:(NSString*)pushmessage withTitle:(NSString*)title
{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:pushmessage delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
if (alertView)
{
}
}
in myviewcontroller:
-(void)insert:(NSDate *)fire
{
appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.localNotification = [[UILocalNotification alloc] init];
NSLog(#"localNotification %#", appDelegate.localNotification);
if (appDelegate.localNotification == nil)
return;
appDelegate.localNotification.fireDate = fire;
appDelegate.localNotification.timeZone = [NSTimeZone defaultTimeZone];
appDelegate.localNotification.alertBody = appDelegate.str_Motivation;
appDelegate.localNotification.alertAction = #"View";
appDelegate.localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",appDelegate.str_Alarm];
appDelegate.localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
NSLog(#"localNotification.alertBody %#", appDelegate.localNotification.alertBody);
NSLog(#"localNotification.soundName %#",appDelegate.localNotification.soundName);
[[UIApplication sharedApplication] scheduleLocalNotification:appDelegate.localNotification];
}
Please Help.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
......
......
if (localNotif)
{
localNotif.alertBody = [NSString stringWithFormat:
NSLocalizedString(#"%# has a message for you.", nil), str_friend];
localNotif.alertAction = NSLocalizedString(#"Read Msg", nil);
localNotif.soundName = #"alarmsound.caf";
localNotif.applicationIconBadgeNumber = 1;
[localNotif setRepeatInterval:NSMinuteCalendarUnit];
[application presentLocalNotificationNow:localNotif];
str_friend = nil;
break;
}
}
I got solution.
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.
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.