Switching ON and OFF the Alarm ios - ios

I have prepared an Alarm Clock app which uses UILocalnotification for scheduling the alarm.Now after the alarm has been set, I want to make a switch so that I can turn it ON and OFF usingUISwitch.I just cant figure how can I do that?What I am thinking as of now is that when you switch OFF the alarm, I shall store the DATE and TIME value before canceling the UILocalnotification so that when the user again switch ON the alarm I reschedule it with the stored DATE and TIME values. Is it the right way to do or is there any other ways to do that?

just make the database table which have 'date', 'isCanceled' field and unique id 'alarmId' columns (use rest whatever you want). so when the user wants to cancel the alarm try this,
NSString *alarmId = #"some_id_to_cancel";
UILocalNotification *notificationToCancel=nil;
for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if([aNotif.userInfo objectForKey:#"ID"] isEqualToString:alarmId]) {
notificationToCancel = aNotif;
break;
}
}
[[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];
to use this better you create your alarm by,
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.alertBody = title;
localNotif.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:stringID forKey:#"ID"];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

Related

Canceling UILocalNotification

I'm currently trying to cancel specific UILocalNotifications associated with objects in my data model. To do this, each data object has a unique identifier, which is an NSUUID.
Create UILocalNotification:
/* Set UILocalNotification */
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
localNotification.alertBody = self.mytextfield.text;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
NSLog(#"making a notification: %#",[r.uniqueId UUIDString]);
[localNotification.userInfo setValue:[r.uniqueId UUIDString] forKey:#"uid"];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
Yet when I go to delete the notification and print out each notifications contents, the alertbody of the notifications are printed correctly but the unique identifier is somehow lost. What's wrong with this implementation?
Cancel UILocalNotification:
Obj *r = (Obj *)[self.objects[indexPath.section] objectAtIndex:indexPath.row];
/* Cancel UILocalNotification */
NSArray *scheduleReminders = [[UIApplication sharedApplication] scheduledLocalNotifications];
NSLog(#"scheduled.count: %i",(int)scheduleReminders.count); // Correctly prints 3
for (int i = 0; i < scheduleReminders.count; i++)
{
UILocalNotification *notification = scheduleReminders[i];
NSDictionary *userInfoCurrent = notification.userInfo;
NSLog(#"searching through reminders: %i %# %# %#",(int)i,[userInfoCurrent objectForKey:#"uid"], notification.alertBody); // Alert body prints correctly
if ([[userInfoCurrent valueForKey:#"uid"] isEqualToString:[r.uniqueId UUIDString]])
{
NSLog(#"found it");
//Cancelling local notification
[[UIApplication sharedApplication] cancelLocalNotification:notification];
break;
}
}
The problem is that userInfo is "nil" by default. You should allocate your own NSDictionary, set uid and then set this dictionary to localNotification.userInfo.

WebServices Call when application in Background and show the response in Local Notification

I have an enterprise application that I want to keep running, so it can call a webservice and inform to the user through Local Notification.
So, it now runs in the background, it makes the calls, gets results, informing to the user.
I Used a timer in applicationDidEnterBackground. My Code is,
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
NSLog(#"ENTER BACKGROUND");
if (UIApplication.sharedApplication.applicationState == UIApplicationStateBackground)
{
backgroundTimer=nil;
[backgroundTimer invalidate];
backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(backgroundTasks) userInfo:nil repeats:YES];
}
application.applicationIconBadgeNumber = 0;
}
When the timer is triggered, i will check the date condition. If Date is matched then i have to make webservice call.
-(void)backgroundTasks
{
NSDate *CurrentDate = [NSDate date];
NSDate *previousDate = [[NSUserDefaults standardUserDefaults]valueForKey:#"ScheduledTime"];
NSLog(#"Current Date : %# - Previous Date : %#",CurrentDate,previousDate);
NSString *CurrentdateString = [NSString stringWithFormat:#"%#",CurrentDate];
NSString *PreviousdateString = [NSString stringWithFormat:#"%#",previousDate];
NSLog(#"Current Date String : %# - Previous Date String : %#",CurrentdateString,PreviousdateString);
if ([PreviousdateString isEqualToString:CurrentdateString])
{
NSLog(#"Both dates are same");
previousDate = [previousDate dateByAddingTimeInterval:60];
[[NSUserDefaults standardUserDefaults] setObject:previousDate forKey:#"ScheduledTime"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self updateUserLatLong:str_Latitude :str_Longitude]; //Webservices call
}
else
{
NSLog(#"Dates are different");
}
}
I got the response from this request, at that time i will create Local Notification. like this,
str_Condition = [NSString stringWithFormat:#"%#",[conditionarray lastObject]];
str_TempFaren = [NSString stringWithFormat:#"%#",[mutArr_High lastObject]];
NSLog(#"Condition : %#, Temperature : %#",str_Condition,str_TempFaren);
NSLog(#"SHOW ALERT NOTIFICATION");
NSLog(#"-----------------------------------------------------------------------");
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [NSDate date];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:#"%#° F - %#, See today's recommendations",str_TempFaren,str_Condition];
localNotif.alertAction = #"Reminder";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber =0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];
I Create Default Notification in another class, like this.
pickerDate = [datePicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = #"See today's recommendations";
localNotification.alertAction = #"Reminder";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSMinuteCalendarUnit;
// localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
My Problem is, when the user remove the application from memory, obviously we can't make any webservices call. So when the app is removed from the memory, i want to show the message in localnotification which contains default alertbody. Now Both scenarios are working. but i want to display only one notification. if app removed from memory then only i have to show default notification. How to handle this problem, Please help me. i was strucked more than 7 hours for this issue.
I found the answer by myself. Solution is, I create the default UILocalNotification in the method,
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NSDate *pickerDate = [[NSUserDefaults standardUserDefaults]valueForKey:#"ScheduledTime"];
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = #"See today's recommendations";
localNotification.alertAction = #"Reminder";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSHourCalendarUnit;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
application.applicationIconBadgeNumber = 0;
}
So, when i remove the app from memory. That time i create this notification.

How to delete n UILocalNotification permanently?

I tried doing NSLog(#"The notifications is \n %#",notification);
And the log message is : 2013-10-18 12:23:36.010 Remainder[2433:207] The notifications is {fire date = (null), time zone = Asia/Kolkata (IST) offset 19800, repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Friday, October 18, 2013 12:23:36 PM India Standard Time}
IF returned null then the notifications are not Returned. So try this instead
Method1:
-(void) scheduleNotificationForDate:(NSDate *)date AlertBody:(NSString *)alertBody ActionButtonTitle:(NSString *)actionButtonTitle NotificationID:(NSString *)notificationID{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
localNotification.timeZone = [NSTimeZone localTimeZone];
localNotification.alertBody = alertBody;
localNotification.alertAction = actionButtonTitle;
localNotification.soundName = #"yourSound.wav";
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:notificationID forKey:notificationID];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
Method2:
Once you set notification,the only way to edit it ,is canceling the old one and recreate another one,so you can do this way,searching your existing one and cancel it.
`for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
if([[aNotif.userInfo objectForKey:#"id"] isEqualToString:nId])
{
[[UIApplication sharedApplication]cancelLocalNotification:aNotif];
}
}`
For delete specific notification
[[UIApplication sharedApplication] cancelLocalNotification: notification];
And cancel all notification
[[UIApplication sharedApplication] cancelAllLocalNotifications];
you have to delete a particular scheduled notification you have to use the below method.
[[UIApplication sharedApplication] cancelLocalNotification: notification];

Perform Action At DatePicker Time

I need to send a text message when the current time equals the time selected in the UIDatePicker. How might I do this? You don't need to include the code to send the message, I already have that coded. I've tried all sorts of things with NSTimer and if - then statements but none have worked.
Edit: Since I wrote this question I've found a better way to do things. I just need to set a local notification and when received execute my code with -(void)didRevieveLocalNotification. Here is what I have so that any googlers can hopefully be helped.
NSDate *pickerDate = [self.datePicker date];
//Set Local Notification
UILocalNotification *notif = [[UILocalNotification alloc] init];
notif.fireDate = pickerDate;
notif.timeZone = [NSTimeZone defaultTimeZone];
//----------------------------------------------------------------------
notif.alertBody = #"Tap to send your text message!";
notif.alertAction = #"send message...";
notif.soundName = #"sms_alert_nova.caf";
notif.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
well i would use a local notification... something like this
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = theDate //The date that your picker has selected
notification.alertBody = #"Hey, the time just expired!"
notification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
Then in your AppDelegate
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//Code to manage the notification logic
}
Hope this helps, the user will get the alert even if on background.. if on background the user must click the alert to let your application know that the local notification triggered, if he does (or he is on your app already, then the app delegate method will trigger letting your app know that the notification fired...
Hope this helps!

how to identify a particular notification in ios sdk

actually am developing an alarm project,
now i have a doubt on Local notification. how can i identify a particular notification.
we can't even set tag to local notification then how can i differentiate them.
example:
notification:1
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = selectedDate;
localNotification.alertBody = #"you got work";
localNotification.alertAction = #"Snooze";
localNotification.repeatInterval = NSDayCalendarUnit;
localNotification.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:#"setNotificationForEveryDay", #"key", nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
notification:2,
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = another selectedDate;
localNotification.alertBody = #"i got work";
localNotification.alertAction = #"Snooze";
localNotification.repeatInterval = NSDayCalendarUnit;
localNotification.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:#"setNotificationForEveryDay", #"key", nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
now i'm in situation to delete the second notification how can i do it...
please help me..
thanks in advance..
My guess is that use the userInfo for distinguishing the local notifications that would be a better idea but for that you need to set the userInfo of the local notification.
Like you could do something like this
if ([Your_notification_Object.userInfo valueForKey:#"Key 1"]==#"Object 1") {
NSLog(#"This is notification 1");
}
now for your second requirement i.e for the deleting part do you want to delete the notification when it is identified as n1 or n2 then in that case you could modify the above code and add this
if ([Your_notification_Object.userInfo valueForKey:#"Key 1"]==#"Object 1") {
NSLog(#"This is notification 1");
[[UIApplication sharedApplication] cancelLocalNotification:Your_notification_Object];
}
Place the above code as per your convenience

Resources