Weekly Local Notification Showing Array Values - Swift - ios

So let's say I have code like the below local notification code. It runs weekly. How do I change the alertBody string to cycle through an array of messages? My desired end result is that every week it shows array[i], where each time array[i] is incremented +1.
func weeklyNotifications () {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 60*60)
localNotification.alertBody = "Weekly array string"
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = NSCalendarUnit.WeekOfYear
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.category = "Message"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}

The notification can not cycle the body from an array, the only way is to schedule the notifications yourself (create one for each week) in a loop, and change the body accordingly.

for var i = 0; i < alertBodyMessage.count; i++ {
notification.alertBody = alertBodyMessage[i]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
you'll have to schedule a notification with alert message from your datasource

Related

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.

using UILocalNotification with randomising strings

I have implemented UILocalNotification success on my project which i failed on randomising strings came from NSDictionary that i need to send whole worlds in each every 5 minute period. In every 5 minute, i need to pass random string in UILocalNotification.
Here is my example code :
NSArray *word1Array= [_tmp objectForKey:#"word1"];
NSArray *word2Array = [_tmp objectForKey:#"word2"];
if([word1Array count] > 0)
{
int minCount = 0;
int totalcount = (int)[word1Array count];
int randomIndex = (arc4random()%(totalcount-minCount))+minCount;
NSString *word1 = [word1Array objectAtIndex:randomIndex];
NSString *word2 = [word2Array objectAtIndex:randomIndex];
NSString *wordbody = [NSString stringWithFormat:#"%# - %#",word1,word2];
UILocalNotification *reminderNote = [[UILocalNotification alloc]init];
reminderNote.repeatInterval = NSMinuteCalendarUnit;
reminderNote.alertBody = wordbody;
reminderNote.alertAction = #"Bak";
reminderNote.soundName = #"sound.aif";
reminderNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:60 * 5];
reminderNote.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
}
This codes starts to send notification with randomised strings but every 5 minutes, it passed 4-5 words same time which is really annoying. How can i fixed it for just sends 1 string in each 5 minute ?
If I understand your problem correctly, you get the same string for N times at minute 5th. It is because you schedule the Local Notification at the same time.
You should put the above code into something like:-
for(int i=1;i<=5 ;i++){
//Your other code
reminderNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:60 * 5 * i];
//Your other code
}
The above code will schedule to local notification for 5 times, it will notify the user at minute 5, 10, 15, 20, 25 from the current time.
Update Answer:-
Each application on a device is limited to 64 scheduled local
notifications. The system discards scheduled notifications in excess
of this limit, keeping only the 64 notifications that will fire the
soonest. Recurring notifications are treated as a single notification.
See: https://developer.apple.com/Library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/WhatAreRemoteNotif.html
Schedule a new Local Notification after another: UILocalNotification with various alert body

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;
...
...
}

Local Notification Ever Changing Text

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.

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