Local Notification Ever Changing Text - ios

I am working on getting local notifications to fire at a time every day (set by the user). I have done this in the past, but just where it was one static message that would get shown every day. I would like for it to take the text for the local notification from a plist file I have made with each row being a quote. Is there a way to fire local notifications, but have it change the text every day?
I have right now:
- (IBAction)scheduleNotification {
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [datePicker date];
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.alertBody = #"Today's 5 Minutes With God Study Is Now Available";
notif.alertAction = #"Ok";
notif.soundName = UILocalNotificationDefaultSoundName;
notif.applicationIconBadgeNumber = 1;
NSInteger index = [scheduleControl selectedSegmentIndex];
switch (index) {
case 0:
notif.repeatInterval = NSDayCalendarUnit;
break;
case 1:
notif.repeatInterval = 0;
break;
}
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"Today's Quote!"
forKey:kRemindMeNotificationDataKey];
notif.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[self.notifications addObject:notif];
[notif release];
}
}
So, how would I get the alertBody to show a different message each day?

You have to create a new notification every time, for every new message.

Related

How to make register notification in Objective C?

I have an online radio. The radio has programs at different times, programs are displayed in a list.
My need is that when one tap and hold on the list of program he schedule a notification to the User.
examplo program in list:
Tap and hold is already running (code below):
-(void)registerHour:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint ponto = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:ponto];
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.imageAgendamento.hidden = false;
NSString *test = [ NSString stringWithFormat:#"%#",[[results objectAtIndex:indexPath.row] objectForKey:#"hour" ]];
NSLog(#"hour -> %#", test);
}
}
The test is where has the time of notification "09:00" (in direct
format JSON)
appDelegate.m i add:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
}
Looked at several tutorials and researched in various places, I could not solve my problem any way. What I need to do to get this notification schedule?
You can send a 5 min delayed local notification using the code below:
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDate *currentDate = [NSDate date];
[dateComponents setMinute:5];
NSDate *fireDate = [gregorian dateByAddingComponents:dateComponents toDate:currentDate options:0];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// Configure the notification
// ....
//
localNotification.fireDate = fireDate;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
But I think what you need to do is using an NSTimer or simply the performSelector:withObject:afterDelay: method of NSObject.

UILocalNotification getting called repetitively as the app launches

I don't know what is the problem here but everytime I run my app , local notifications get called repetitively showing fireDate as NULL.I am trying to take care of this issue from the past 5hrs now.I need help!!!
"<UIConcreteLocalNotification: 0x7f872ead7630>{fire date = (null), time zone = (null), repeat interval = NSCalendarUnitDay, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Monday, 7 September 2015 5:32:44 pm India Standard Time, user info = (null)}",
I have done enough research on UILocalNotification to get started with it,but i'm still facing this problem.
-(void)setDate:(NSDate*)myfireDate andTime1InString: (NSString*)time1Str andTime2InString:(NSString*)time2Str andTime3InString:(NSString*)time3Str{
//concatenate myFireDate with all three times one by one
NSString *myFireDateInString = [dateFormatter stringFromDate:myfireDate];
myFireDateInString = [myFireDateInString stringByAppendingString:#" "];
NSString *dateWithTime1InString = [myFireDateInString stringByAppendingString:time1Str];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateWithTime1 = [dateFormatter dateFromString:dateWithTime1InString];
NSString *mySecondFireDateInString;
NSString *dateWithTime2InString;
NSDate *dateWithTime2;
if ([time2Str length] !=0){
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
mySecondFireDateInString = [dateFormatter stringFromDate:myfireDate];
mySecondFireDateInString = [mySecondFireDateInString stringByAppendingString:#" "];
dateWithTime2InString = [mySecondFireDateInString stringByAppendingString:time2Str];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateWithTime2 = [dateFormatter dateFromString:dateWithTime2InString];
}
NSString *myThirdFireDateInString;
NSString *dateWithTime3InString;
NSDate *dateWithTime3;
if ([time3Str length]!=0){
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
myThirdFireDateInString = [dateFormatter stringFromDate:myfireDate];
myThirdFireDateInString = [myThirdFireDateInString stringByAppendingString:#" "];
dateWithTime3InString = [myThirdFireDateInString stringByAppendingString:time3Str];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateWithTime3 = [dateFormatter dateFromString:dateWithTime3InString];
}
NSLog(#"%#",dateWithTime3);
NSLog(#"%#",dateWithTime2);
//block starts here
void(^notificationBlock)(void) = ^{
appDelegate.localNotification1 = [UILocalNotification new];
appDelegate.localNotification1.fireDate = dateWithTime1;
appDelegate.localNotification1.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
if(dateWithTime2 != nil){//Make a new UILocalNotification object
appDelegate.localNotification2 = [UILocalNotification new];
appDelegate.localNotification2.fireDate = dateWithTime2;
appDelegate.localNotification2.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
}
if(dateWithTime3 !=nil){//MAke a new UILocalNotification object
appDelegate.localNotification3 = [UILocalNotification new];
appDelegate.localNotification3.fireDate = dateWithTime3;
appDelegate.localNotification3.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber]+1;
}
if([_repeatDaysTextField.text isEqualToString:#"Everyday"]){
// appDelegate.localNotification1.alertBody = #"Time to take your medicine";
appDelegate.localNotification1.repeatInterval = kCFCalendarUnitDay;
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification1];
if(dateWithTime2 != nil){
appDelegate.localNotification2.repeatInterval = kCFCalendarUnitDay;
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification2];
appDelegate.localNotification2.alertBody = #"Not2";
NSLog(#"%#",appDelegate.localNotification2);
}
NSLog(#"%#",[NSString stringWithFormat:#"%#",dateWithTime3 ]);
if(dateWithTime3 != nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification3];
}
}
else if([_repeatDaysTextField.text isEqualToString:#"Alternately"]){
}
else if([_repeatDaysTextField.text isEqualToString:#"Weekly"]){
appDelegate.localNotification1.repeatInterval = kCFCalendarUnitWeekday;
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification1];
if(dateWithTime2!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification2];
}
if(dateWithTime3!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification3];
}
}
else if([_repeatDaysTextField.text isEqualToString:#"Bi-Weekly"]){
}
else if([_repeatDaysTextField.text isEqualToString:#"Monthly"]){
appDelegate.localNotification1.repeatInterval = kCFCalendarUnitMonth;
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification1];
if(dateWithTime2!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification2];
}
if(dateWithTime3!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification3];
}
}
else if([_repeatDaysTextField.text isEqualToString:#"Yearly"]){
appDelegate.localNotification1.repeatInterval = kCFCalendarUnitYear;
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification1];
if(dateWithTime2!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification2];
}
if(dateWithTime3!=nil){
[[UIApplication sharedApplication]scheduleLocalNotification:appDelegate.localNotification3];
}
}
};
//block ends here
//method to set notification
[self setNotification:notificationBlock];
}
-(void)setNotification:(void(^)(void))setNotificationBlock{
setNotificationBlock();
}
I got the solution.In the method,didReceiveLocalNotification:,I was adding the notification object to the 'scheduledNotifications' array.So every time a notification was scheduled,the same object was being added to the 'scheduledNotifications' array and that was getting fired again and again.
[UIApplication sharedApplication]scheduledNotifications = notification;
NOTE:Ignore this statement in didReceiveLocalNotification:
This is occuring beacuse you are setting
appDelegate.localNotification.repeatInterval = someUnit;
try setting the repeatInterval value to 1 by checking whether the repeatCount is 0 or not.

UILocalNotification triggered but not scheduled

Hi people I have a problem with my app, where I want to add some basic LocalNotifications, which repeat themselves every week. I want to do this in a method called "scheduleLocalNotificationForItem:", which is called when the doneBarButtonItem is pressed. This all seems to be working so far, because when I log all the scheduled notifications every scheduled notification shows up. But when I use the app, the scheduled notifications get triggered and show up but there are some additional notifications, which I haven't set myself and I can't determinate where they come from, which appear too.
So here's my code:
- (int)scheduleNotifitactionsForItem:(AlarmItem *)item
{
NSArray *reorderdRepeat = [NSArray arrayWithArray:[self transformArray:item.repeat]];
int missedDays = 0;
int scheduledAlarms = 0;
for (int i = 0; i < item.repeat.count; i++) {
if ([[reorderdRepeat objectAtIndex:i] boolValue] == true) {//Problem determinating true values at end of array
NSInteger integerOfDay = i + 1;//reorderRepeat should contain seven items, icrement i bevore adding it to integerOfDay
NSDate *lastAlarmTime = [self getFireDateForDayOfWeek:integerOfDay withTime:item.time];
NSArray *allAlramTimesForDay = [self getFireDatesForTime:lastAlarmTime andCycle:item.cycles];
for (int i = 0; i < allAlramTimesForDay.count; i++) {
NSDate *alarmTime = [allAlramTimesForDay objectAtIndex:i];
UIApplication *application = [UIApplication sharedApplication];
UILocalNotification *notification = [UILocalNotification new];
NSDictionary *userInfo = #{#"index":[NSString stringWithFormat:#"%d",item.notification]};
notification.repeatInterval = NSCalendarUnitWeekday;
notification.alertBody = item.title;
notification.userInfo = userInfo;
notification.fireDate = alarmTime;
notification.soundName = item.sound;
[application scheduleLocalNotification:notification];
scheduledAlarms += 1;
}
} else {
missedDays += 1;
}
}
return scheduledAlarms;
}
Help is appreciated ;)
Your repeatInterval should be NSCalendarUnitWeekOfYear (or old NSWeekCalendarUnit). NSCalendarUnitWeekday (NSWeekdayCalendarUnit) will repeat everyday.

Trying to create UILocalNotification repeating every weekday

I'm trying to create a repeating local notification using Xamarin.IOS. I want to have different alert body message each day, for example "It's monday", "It's tuesday" and so on.
The problem I have is that the only the first notification is working. After I've read the documentation and a few tutorials the correct way to create a repeating notification is to loop through each day and create a total of seven notifications that has the RepeatInterval property set to NSCalendarUnit.Weekday.
My code is a bit messy at the moment...
for (int i = 0; i <= 6; i++) {
NSDateComponents components = gregCalendar.Components (NSCalendarUnit.Day | NSCalendarUnit.Year | NSCalendarUnit.Month, DateTime.Now.AddDays(i).ToNSDate());
components.Day = DateTime.Now.AddDays(i).Day;
components.Month = DateTime.Now.AddDays(i).Month;
components.Year = DateTime.Now.AddDays(i).Year;
NSDate referenceDate = gregCalendar.DateFromComponents (components);
NSDateComponents componentsForFireDate = gregCalendar.Components (NSCalendarUnit.Year | NSCalendarUnit.Hour | NSCalendarUnit.Minute, referenceDate);
componentsForFireDate.Year = components.Year;
componentsForFireDate.Month = components.Month;
componentsForFireDate.Day = components.Day;
componentsForFireDate.Hour = 8;
componentsForFireDate.Minute = 0;
var dayOfWeek = (int)DateTime.Now.AddDays (i).DayOfWeek + 1;
if (dayOfWeek == 8)
dayOfWeek = 1;
componentsForFireDate.Weekday = dayOfWeek;
NSDate fireDateOfNotification = gregCalendar.DateFromComponents (componentsForFireDate);
UILocalNotification localNotification = new UILocalNotification ();
localNotification.FireDate = fireDateOfNotification;
localNotification.TimeZone = NSTimeZone.LocalTimeZone;
localNotification.AlertBody = dayOfWeek;
localNotification.AlertAction = "daily";
localNotification.RepeatCalendar = NSCalendar.CurrentCalendar;
localNotification.RepeatInterval = NSCalendarUnit.Weekday;
localNotification.ApplicationIconBadgeNumber = 1;
UIApplication.SharedApplication.ScheduleLocalNotification (localNotification);
}
My question is, how can I create a local notification that should repeat every day but with different alert body message depending on the weekday?
Add this code into you for loop
switch(i)
{
case 0: //mon
localNotification.alertbody = #"Monday....you message";
break;
case 1 //tue
localNotification.alertbody = #"Tuesday....you message";
break;
case 2://wed
localNotification.alertbody = #"Wednesday....you message";
break;
...
...
}

Can I reduce code in repeat declarations?

Is there a way to reduce code for repeat declarations in Obj-C?
E.g.:
I have
localNotification.fireDate = self.dueDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = self.text;
localNotification.soundName = UILocalNotificationDefaultSoundName;
Can it be simplified to something like this?
localNotification
.fireDate = self.dueDate;
.timeZone = [NSTimeZone defaultTimeZone];
.alertBody = self.text;
.soundName = UILocalNotificationDefaultSoundName;
Thanks!
You could use Key-Value-Coding. First pack the values into a dictionary with the property names as keys
NSDictionary *parameters = #{#"fireDate": self.dueDate,
#"timeZone":[NSTimeZone defaultTimeZone],
#"alertBody":self.text,
#"soundName": UILocalNotificationDefaultSoundName }
, than you can easily enumerate the keys and objects with a block.
[parameters enumerateKeysAndObjectsUsingBlock: ^(id key,
id object,
BOOL *stop)
{
[localNotification setValue:object forKey:key];
}];
If you would use this code over and over again, I'd create a category on NSNotification wth an method that takes the dictionary and dies the enumeration.
Than you can simply use
[localNotification setValuesForKeysWithDictionary:parameters];
docs
Of course you can write it even shorter:
[localNotification setValuesForKeysWithDictionary:#{#"fireDate": self.dueDate,
#"timeZone":[NSTimeZone defaultTimeZone],
#"alertBody":self.text,
#"soundName": UILocalNotificationDefaultSoundName }];
Now it is nearly as compact as the proposed syntax.
The only way would be to declare a method that takes the parameters you are wanting to set.
-(void)notification:(UILocalNotification *)notification setFireDate:(NSDate *)date
setAlertBody:(NSString *)alertBody {
notification.fireDate = date;
notification.alertBody = alertBody;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
}
The second two lines could be considered setting up a "default". Change those lines to whatever a default value you'd want. Then...
UILocalNotification *myNotification = ...
NSDate *tenMinutesAway = [NSDate ...
[self notification:myNotification setFireDate:tenMinutesAway setAlertBody:#"Hello world!"];
You could also look at subclassing UILocalNotification and in the -init method set up a bunch of default behavior there, which would save you ever having to type .soundName and .timeZone again

Resources