How do I make UILocalNotification method keep running - ios

I am trying to build a calendar style app that reminds people when certain events are happening the day before they happen.
I am using UILocalNotifications for this.
I have to restart my app if I want the notification to appear.
How can I have this code continuously run regardless if the app is still running or is closed, and display the notification on time?
I was wondering if I had to put this into the applicationDidEnterBackground method to make it work?
Currently my code looks like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMMM dd, yyyy"];
NSString* path = [[NSBundle mainBundle] pathForResource:#"example"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* allLinedStrings = [content componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
NSDate *tomorrow = [today dateByAddingTimeInterval:60*60*24*1];
NSString *tomorrowString = [dateFormatter stringFromDate:tomorrow];
for (int i = 0; i < allLinedStrings.count; i++) {
NSString* strsInOneLine = [allLinedStrings objectAtIndex:i];
NSArray* singleStrs = [strsInOneLine componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#";"]];
NSString *date = [singleStrs objectAtIndex:0];
if ([date isEqualToString:tomorrowString]) {
for (int j = 1; j < singleStrs.count; j+=2) {
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = [NSDate dateWithTimeInterval:60*60*-24 sinceDate:tomorrow];
notification.alertBody = [singleStrs objectAtIndex:j+1];
notification.alertTitle = [singleStrs objectAtIndex:j];
notification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
}
}
// Override point for customization after application launch.
return YES;
}

Your app code does not need to be running for your local notification to be displayed. Once your app has called scheduleLocalNotification:, the notification will display whether or not you app is running.
If you app is in the foreground, you will also want to implement application:didReceiveLocalNotification:. If you want your app to respond to being opened by the user interacting with the notification, you will want to implement application:handleActionWithIdentifier:forLocalNotification:completionHandler:
As to the question of where to put the code that schedules the notification, it should go anywhere in your app that knows the event to be scheduled. It only needs to be called once per notification. It can be scheduled far in advance.

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.

Refresh View and Data everytime app opens

I have a TableView that needs to be refreshed every time the app opens, but I can't get it to do that.
The reason for this, is that there is new data for every day stored in a JSON file, so the app needs to refresh to find out if its a new day so it can load the new data.
I tried moving my code from viewDidLoad to viewWillAppear thinking that would do the trick, but it didn't.
Any ideas?
ViewController.m
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Get current date, remove year from current date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
NSString *dateTodayShort = [dateToday substringToIndex:[dateToday length] -6];
// Get JSON file path
NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:#"Days" ofType:#"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
days = JSONDictionary[#"days"];
// Iterate thru JSON to find Data for Today
NSObject *todayJson;
for (NSObject *object in days) {
NSString *dateObject = [object valueForKey:#"day"];
if ([dateObject isEqualToString:dateTodayShort]) {
todayJson = object;
NSString *textToday = [todayJson valueForKey:#"text"];
NSString *backgroundImageToday = [todayJson valueForKey:#"backgroundImage"];
textGlobal = textToday;
backgroundImageGlobal = backgroundImageToday;
}
}
// Other set up code...
}
I had a similar issue recently, my misunderstanding was that viewWillAppear / viewDidAppear would be called whenever the app opens (and the corresponding view controller is shown). That is in fact no the case!
How you do this is by adding an observer for a NSNotification like so:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateData) name:UIApplicationDidBecomeActiveNotification object:nil];
iOS sends a system NSNotification when your app is launched. The name of the notification is held in the constant UIApplicationDidBecomeActiveNotification. You can add your UITableViewController that holds the data (or any other class for that matter) as an observer for that notification and perform the update whenever the notification is received.

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.

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.

Resources