Local Notification on ViewController - iphone

I have the following code in ViewController.m:
-(void) checker {
UILocalNotification *notification = [[UILocalNotification alloc] init];
[notification setAlertBody: #"Im your local notification"];
[notification setFireDate: [NSDate dateWithTimeIntervalSinceNow: 1]];
[notification setTimeZone: [NSTimeZone defaultTimeZone]];
[UIApplication setScheduledLocalNotifications: [NSArray arrayWithObject: notification]];
}
The last line produces a warning:
Class method '+setScheduledLocalNotifications' not found (return type defaults to id)
and it gives error while processing. How can I instantiate the notification? As I said I am new, if you can provide a complete answer it will be greatly appreciated.
Edit: I have a timer that repeats itself every 60 seconds and calls a function that puts a notification.
timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:#selector(checker) userInfo:nil repeats:YES];
/* ... */
-(void)checker {
NSLog(#"Notification routine");
UIApplication* app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
// Clear out the old notification before scheduling a new one.(if needed)
if ([oldNotifications count] > 0)
[app cancelAllLocalNotifications];
// Create a new notification.
UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease];
if (alarm) {
alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.alertBody = #"Msg to show";
[app scheduleLocalNotification:alarm];
}
}
I can see the log only firing once a minute, but the oldNotifications count does not increase.

[[UIApplication sharedApplication] scheduleLocalNotification:notification];
the '+' in the error message means it is trying to call a class method rather than an instance method. The [UIApplication sharedApplication] call will return the singleton instance of the application object that allows you to call that method as an instance method.
Also you should read the documentation for UIApplication. You just need to call scheduleLocalNotification: with the notification object to get it scheduled. This will allow you to release the memory to the object, because the schedule method will copy the object.

This is how I do it,
UIApplication* app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
// Clear out the old notification before scheduling a new one.(if needed)
if ([oldNotifications count] > 0)
[app cancelAllLocalNotifications];
// Create a new notification.
UILocalNotification* alarm = [[[UILocalNotification alloc] init] autorelease];
if (alarm)
{
alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:60*60];//afterone hour
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.soundName = #"alarmsound.caf";
alarm.alertBody = #"Msg to show";
[app scheduleLocalNotification:alarm];
}
update:
- (void)scheduleAlarmForDate:(NSDate*)theDate andBody:(NSString*)Body
{
UIApplication* app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
// Clear out the old notification before scheduling a new one.
if ([oldNotifications count] > 0)
[app cancelAllLocalNotifications];
// Create a new notification.
UILocalNotification* alarm = [[UILocalNotification alloc] init];//Using ARC no autorelease
if (alarm)
{
alarm.fireDate = theDate;
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.soundName = #"alarmsound.caf";
alarm.alertBody = Body;
[app scheduleLocalNotification:alarm];
}
}
now if I call this method twice,
NSDate *fireDate1 = [NSDate dateWithTimeIntervalSinceNow:4.0];
[self scheduleAlarmForDate:fireDate1 andBody:#"My alertBody 1"];
NSDate *fireDate2 = [NSDate dateWithTimeIntervalSinceNow:6.0];
[self scheduleAlarmForDate:fireDate2 andBody:#"My alertBody 2"];
the first alarm will be canceled,,

Related

iOS accelerometer in the background (infinite)

I would like my app to monitor my accelerometer for an infinite time (even in the background). When it reaches a certain amount, I would like to deliver a local notification. This is exactly the same functionality as the 'Sleep Cycle' app has.
But how did they do this? When I use the beginBackgroundTaskWithExpirationHandler function, it isn't working anymore after 10 minutes. Adding UIBackgroundModes doesn't help at all.
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
_motionManager = [[CMMotionManager alloc] init];
_motionManager.accelerometerUpdateInterval = 1;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[_motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"%#",accelerometerData);
if(accelerometerData.acceleration.x > 0.5){
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [NSDate date];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"Wake up!";
localNotif.alertAction = #"wake";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 4;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
To run your app infinitely in background, you need to provide the UIBackgroundModes value in Info.plist file.
https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW20

removing Notifications

I made an app that has custom notifications, but I cant remove them no matter what I do.
[[UIApplication sharedApplication] cancelLocalNotification:[idkey objectAtIndex:indexPath.row]];
That is the code I use for removal; If I use all it works. The idkey is the correct
value, and its a number in a string, #"3" in this case.
This is a part of the saving function:
-(void) addNewNotificationWithKey:(NSString*)key {
NSLog(#"%#",key);
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [tempFormatter dateFromString:datuminura];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = description1;
notif.alertAction = #"Open";
notif.soundName = UILocalNotificationDefaultSoundName;
Is it right?
Check which notification you want to remove and use following code to cancel it.
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
[EDIT]
Add following line into your local notification to make [uid isEqualToString:uidtodelete] condition work.
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"%d",[idkey objectAtIndex:indexPath.row]] forKey:#"uid"];
notif.userInfo = infoDict;

Appdelegate function 'didreceivelocalnotification' is called immediately after the notification is created

I'm using UILocalNotifications in iPhone to create an alarm. Alarm is scheduled when I click a UIButton. My issue is that – application:didReceiveLocalNotification: is called when I click this button, that is when I create a local notification. But , – application:didReceiveLocalNotification: should be called only when the notification time is reached. I checked it on both simulator and device and got the same results. Can anyone help me with this...thanks in advance.
-(void)createalarm:(NSString *)datend_time:(NSString *)message//creating alarm
{
NSLog(#"created!!!!!!!!!!!!!");
NSString *datestr = datend_time;
NSString *textstr = message;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *alerttime = [formatter dateFromString:datestr];
UIApplication * app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification)
{
notification.fireDate = alerttime;
//notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = 0;
notification.alertBody = textstr;
notification.soundName = UILocalNotificationDefaultSoundName;
[app scheduleLocalNotification:notification];
[app presentLocalNotificationNow:notification];
}
}
-(void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
NSLOG(#"delegate called")
}
It is because you call
[app presentLocalNotificationNow:notification];
So it shows the notification right after you created it. Remove this line of code.
[app scheduleLocalNotification:notification]; will work just fine and will shot the notification at fireDate.
Here is an example of NSLocalnotification:
-(void) scheduleNotificationForDate: (NSDate*)date {
/* Here we cancel all previously scheduled notifications */
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
NSLog(#"Notification will be shown on: %#",localNotification.fireDate);
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = [NSString stringWithFormat:
#"Your notification message"];
localNotification.alertAction = NSLocalizedString(#"View details", nil);
/* Here we set notification sound and badge on the app's icon "-1"
means that number indicator on the badge will be decreased by one
- so there will be no badge on the icon */
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
Make sure that the date you are setting is not in the past!

how to set NSTimer for alarm application?

I am new in iPhone application development. Now i am developing alarm application for iPhone. In this application i am selected data from UIDataPicker. Then i applied to NSLocalNotification firedate with in alarm button action. It is working first time. Then second time agin click that button i again also working, but time also same. It is wrongly working.
Here i think i need to us NSTimer. I don't know how to use NSTimer, and also it is working background application also how to set this timer.
following developed code for alarm notification.
- (void) saveButtonAction:(id)sender {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil)
{
Resource *resourceLoader = [[Resource alloc] init];
NSDictionary *prefDic = [resourceLoader getPlistDataAsDictionary:#"preference"];
NSString *musicName;
NSDate *selectedDateTime = [[NSDate alloc]init];
if (prefDic && [prefDic objectForKey:#"alarmtime"]) {
//firstVal_textField.text = [prefDic objectForKey:#"value1"];
NSLog(#"saravanan %#",[prefDic objectForKey:#"alarmtime"]);
selectedDateTime = [prefDic objectForKey:#"alarmtime"];
NSLog(#"saravanan periyasamy %#", selectedDateTime);
musicName = [NSString stringWithFormat:#"%#%#",[prefDic objectForKey:#"alarmmusic"],#".wav" ];
}
UILocalNotification *notif = [[cls alloc] init];
//notif.fireDate = [datePicker date];
notif.fireDate = selectedDateTime;
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Alarm";
notif.alertAction = #"Show me";
//notif.repeatInterval = 0;
//notif.soundName = UILocalNotificationDefaultSoundName;
notif.soundName = musicName;
notif.applicationIconBadgeNumber = 1;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"saravanan"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
}
The set button is wired up to run a
method called
scheduleNotification in the
view controller which uses the
UILocalNotification class to
schedule a notification. The code
looks as follows:
(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 ;
NSDictionary *userDict = [ NSDictionary dictionaryWithObject:reminderText.text
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[ UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}

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.