ViewController:
- (void)viewDidLoad
{
`[super viewDidLoad];`
dateFormatter.dateFormat = #"dd/MM";
timeFormatter.dateFormat = #"HH:mm";
NSString *dateString = [dateFormatter stringFromDate:dateTime];
NSString *timeString = [timeFormatter stringFromDate:dateTime];
if ([dateString isEqual:#"23/06"]) {
if ([timeString isEqual:#"23:30"]) {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = dateTime;
localNotification.alertBody = [NSString stringWithFormat:#"It's 11:30 PM 23th June!"];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
}
AppDelegate:
[[UIApplication sharedApplication] scheduledLocalNotifications];
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil]];
}
The notification isn't receiving when time equals string and date.
Please help!
The core issue with this (aside from using strings to compare dates) is that viewDidLoad gets called only once in this application. Because you are only scheduling the local notification when the current date is 11:30, it will never get called, since you also set the fireDate to the same exact time.
The thing is, local notifications get scheduled prior to the event. In fact, you should set dateTime to the desired schedule time and then set the local notification.
For example:
- (void)viewDidLoad {
[super viewDidLoad];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2016];
[dateComponents setMonth:6];
[dateComponents setDay:23];
[dateComponents setHour:23];
[dateComponents setMinute:30];
dateTime = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = dateTime;
localNotification.alertBody = [NSString stringWithFormat:#"It's 11:30 PM 23th June!"];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
Based on your uploaded code, it looks like you are going to be grabbing the date from the datePicker, so eventually, you will move the UILocalNotification portion to the button method and use [datePicker date] as the fireDate. Meaning, you can ignore the dateComponents part.
Related
I am trying to update the badge count of application when app is closed, can any one tell, can we update it if app is closed? I am using the following code:
NSCalendar *gregCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponent = [gregCalendar components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSDateFormatter *outputFormatterHour = [[NSDateFormatter alloc] init];
[outputFormatterHour setDateFormat:#"HH"];
NSDateFormatter *outputFormatterMin = [[NSDateFormatter alloc] init];
[outputFormatterMin setDateFormat:#"mm"];
int hour = [[outputFormatterHour stringFromDate:_selectTimePicker.date] intValue];
int min = [[outputFormatterMin stringFromDate:_selectTimePicker.date] intValue];
[dateComponent setHour:hour];
[dateComponent setMinute:min];
NSDate *fireDate = [gregCalendar dateFromComponents:dateComponent];
UILocalNotification *localNotification = [[UILocalNotification alloc]init];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[localNotification setAlertTitle:#"Notification"];
[localNotification setAlertBody:#"Body" ];
[localNotification setAlertAction:#"Open App"];
[localNotification setHasAction:YES];
[localNotification setAlertLaunchImage:#"AppIcon"];
localNotification.applicationIconBadgeNumber++;
[localNotification setFireDate:fireDate];
localNotification.repeatInterval = NSCalendarUnitDay;
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
I need to show certain local notifications while app is in the background. How can I do it, without the help of NSNotificationCenter?
Andrey Chernukha in first comment is right.
Here is the code to implement simple Local Notification:
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.repeatInterval = 0;
NSDate *now = [NSDate date];
NSDate *dateToFire = [now dateByAddingTimeInterval:10];
localNotification.fireDate = dateToFire;
localNotification.alertBody = #"Test local notification";
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
I want to set the daily alarm on the bases of user input. Like user will select time from date picker "10:30", Then i need to set alarm at a that time daily. I write the following code:
func setAlarmAtTime(#time:NSString, withMessage message:NSString){
var loacalNotification = UILocalNotification();
var calendar = NSCalendar.currentCalendar();
calendar.timeZone = NSTimeZone.localTimeZone()
var components = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: NSDate.date());
NSLog("%#",NSDate.date())
NSLog(time);
var timeComponents = time.componentsSeparatedByString(":");
components.hour = timeComponents[0].integerValue;
components.minute = timeComponents[1].integerValue;
if components.isValidDateInCalendar(calendar){
var fireDate = calendar.dateFromComponents(components);
NSLog("%#",fireDate!);
loacalNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay;
loacalNotification.timeZone = NSTimeZone.localTimeZone();
loacalNotification.fireDate = fireDate;
loacalNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay;
loacalNotification.soundName = UILocalNotificationDefaultSoundName;
loacalNotification.alertBody = message;
}
But it shows different time based on time zone following are the behaviour when i try to set alarm at 6:40:
Current Date: 2014-08-12 12:07:21 +0000
Alarm Time: 6:40
Fire Date: 2014-08-12 01:10:00 +0000
I tried to set time zone to local as well as current but nothing works :(
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MMM-yyyy HH:mm"];
NSDate *reminderDate = [df dateFromString:self.lblDate.text];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = reminderDate;
localNotification.alertBody = self.txtName.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.soundName =#"sound.mp3";
NSMutableDictionary *notifyDict = [[NSMutableDictionary alloc] init];
[notifyDict setValue:self.lblType.text forKey:NOTIFICATION_TYPE];
[notifyDict setValue:self.txtName.text forKey:NOTIFICATION_TITLE];
if (![self.tvDescription.text isEqualToString:#"Write Description"]) {
[notifyDict setValue:self.tvDescription.text forKey:NOTIFICATION_DESCRIPTION];
}
[notifyDict setValue:self.lblDate.text forKey:NOTIFICATION_DATE];
localNotification.userInfo = notifyDict;
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self.navigationController popViewControllerAnimated:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
The time that it is given, is in greenwich mean time (GMT)
we just need to set
localNotification.timeZone = [NSTimeZone systemTimeZone];
as it will represent your device or system time zone and schedule your app
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
//localNotification.fireDate = [NSDate dateWithTimeInterval:timeInterval sinceDate:now];
localNotification.fireDate = [NSDate date];
localNotification.repeatInterval = 5*NSSecondCalendarUnit;
localNotification.alertBody = #"Your alert message";
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
This code generates notification after first 5 second then it goes back to NSMinuteCalendarUnit, I have been trying to work around with this but no help.
I want to set notifications every 5 seconds and then it should fire it until i forcefully want to stop it.
Can somebody please help??
The repeatInterval of a UILocalNotification is of type NSCalendarUnit not an time interval. You can only assign a value from the NSCalendarUnit enum to it.
If you want to fire a local notification every 5 seconds you will need to set multiple notifications.
Here is the code.
Use this for every 5 minutes instead of every week.
-(void)setLocalNotificationwithOptions :(NSDictionary *)launchOptions
{
UILocalNotification *localNoti = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNoti) {
NSLog(#"Notification:%#",localNoti);
}
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSCalendar *gregCalendar12 = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponent12 = [gregCalendar12 components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];
[dateComponent12 setWeekday:7];
[dateComponent12 setHour:14];
[dateComponent12 setMinute:46];
UILocalNotification *notification12 = [[UILocalNotification alloc]init];
[notification12 setAlertBody:#"ENJOY YOUR WEEKEND!"];
[notification12 setFireDate:[gregCalendar12 dateFromComponents:dateComponent12]];
notification12.repeatInterval = NSMinuteCalendarUnit;
[notification12 setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:notification12];
}
Hope this helps you. Thank you..
if you want to repeat the timer every 5 seconds,
UILocalNotification allows until 30 seconds per one sound.
So put a 30 seconds sound in your directory,
and then
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *date = "set your notification date"
for (int i = 0; i < 10; i++){
NSDate *repeatTime = [date dateByAddingTimeInterval:300 * i];
notification.fireDate = repeatTime;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
I am working on a application that reminds about the expiry date. I have implemented the same using UILocalNotification with repeat Interval (NSMonthCalendarUnit, NSDayCalendarUnit,NSDayCalendarUnit). For example I have the fire date on 01-01-2012 and the repeat interval is NSDayCalendarUnit and the end date is 12-12-2012, is it possbile to cancelLocalNotification: on expiry.
here is the code:-
- (void) scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtExpiryDate.text, #"ExpiryDate",
txtRegNo.text , #"RegNo",
nil];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.userInfo = userInfo;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
NSLog(#"Repeat Type:%#",txtRepeat.text);
if([txtRepeat.text isEqualToString:#"Every Week"])
{
NSLog(#"Every Week");
localNotification.repeatInterval = 256;
}
else if([txtRepeat.text isEqualToString:#"Every Month"])
{
NSLog(#"Every Month");
localNotification.repeatInterval = NSMonthCalendarUnit;
}
else if([txtRepeat.text isEqualToString:#"Every Day"])
{
NSLog(#"Every Day");
localNotification.repeatInterval = NSDayCalendarUnit;
}
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
NSLog(#"appDelegate.BadgeNumber:%d",appDelegate.BadgeNumber);
localNotification.alertLaunchImage = launchImage;
appDelegate.BadgeNumber = appDelegate.BadgeNumber + 1;
localNotification.applicationIconBadgeNumber = appDelegate.BadgeNumber;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
}
I have worked by comparing current date to expiry date. But this work only if the app is in foreground and i cannot cancelnotification not background for a particular date. Please find the below code for the same:-
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
BadgeNumber = 0;
application.applicationIconBadgeNumber = BadgeNumber;
NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDateFormatter *formatter =[[[NSDateFormatter alloc]init] autorelease];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"localNotifications Count %d",localNotifications.count);
for (UILocalNotification *notify in localNotifications)
{
//notify.applicationIconBadgeNumber = 0;
NSString *ExpiryDateString = [notify.userInfo objectForKey:#"ExpiryDate"];
NSDate *ExpiryDate = [formatter dateFromString:ExpiryDateString];
NSDate * NextFireDate = nil;
NSLog(#"Expiry Date:%#",ExpiryDateString);
if(notify.repeatInterval == NSDayCalendarUnit)
{
NSLog(#"Repeat Every Day");
NextFireDate = [[NSDate date] dateByAddingDays:1];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
if(notify.repeatInterval == NSWeekCalendarUnit)
{
NSLog(#"Repeat Every Day");
NextFireDate = [[NSDate date] addTimeInterval:D_WEEK];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
if(notify.repeatInterval == NSMonthCalendarUnit)
{
NSLog(#"Repeat Every Day");
//NextFireDate = [[NSDate date] addTimeInterval:D_Month];
NextFireDate = [self CalculateExipiryDateForMonth];
NSLog(#"Next FireDate: %#",[formatter stringFromDate:NextFireDate]);
}
NSComparisonResult result = [NextFireDate compare:ExpiryDate];
NSLog(#"NSComparisonResult:%d",result);
if(result == NSOrderedDescending)
{
NSLog(#"Cancell......... Notification");
NSLog(#"notify :::%#",notify);
}
else
{
NSLog(#"Re-Schedule Notification");
BadgeNumber = BadgeNumber + 1;
notify.applicationIconBadgeNumber = BadgeNumber;
NSLog(#"BadgeNumber:%d",BadgeNumber);
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
}
}
}
-(NSDate*) CalculateExipiryDateForMonth
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:[NSDate date] options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];
NSDate *expiryDay = [gregorian dateFromComponents:nextMonthComponents];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = -1;
NSDate *NewExpiry = [gregorian dateByAddingComponents:dayComponent toDate:expiryDay options:0];
[gregorian release];
[dayComponent release];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"Next Exipiry Date -----:%#",[formatter stringFromDate:NewExpiry]);
return NewExpiry;
}
In short, no, you cannot cancel a UILocalNotification while your app is running in the background.
**Apple RESPONSE:-**
I'm responding to your question about UILocalNotification.
At this time UILocalNotification does not have a way to specify an expiry
date or number of repetitions before the notification is automatically
canceled.
The closest you can get today is to schedule up to 64 individual
notifications instead of using the repeat interval.
But you're correct; if the user doesn't ever bring your app to the
foreground, it won't have the opportunity to cancel or reschedule local
notifications.
I highly recommend that you file an enhancement request at <
https://developer.apple.com/bugreporter> asking for this functionality in a
future release of iOS.
You also asked about what happens to local notifications when the user
removes your app from the device. iOS stores the local notifications so
that they are still scheduled if the user deletes and then reinstalls the
app.
When your app runs, it can check the scheduledLocalNotifications property
of UIApplication and remove any notifications that are no longer relevant.
Best regards,
--gc
Garth Cummings
Apple Developer Technical Support