Display a local notification at a fixed time, ios? - ios

I am using the below code to display the notification at a fixed time. However it just does not fit my output.
- (IBAction)bt_set:(id)sender {
// Setting all the information about our date
int hour = 8;
int minutes = 19;
int day = 19;
int month = 10;
int year = 2014;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:day];
[components setMonth:month];
[components setYear:year];
[components setMinute:minutes];
[components setHour:hour];
NSDate *myNewDate = [calendar dateFromComponents:components];
//[components release];
//[calendar release];
[self scheduleNotificationForDate:myNewDate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Note"
message:#"Alarm has been set"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
This is the notfication code
- (void)scheduleNotificationForDate:(NSDate *)date
{
// Here we cancel all previously scheduled notifications
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
NSLog(#"%#",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];
}
This is the date I get in the log
Notification will be shown on: 2014-10-19 02:49:00 +0000
I guess it has something to do with the time zone.
I have the time zone of GMT+5:30
Please help me out

You have some (NSDate *)date----
Add below code to get the appropriate system time:
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

Related

Set Local Notification from Selecting Table cell

Actually This question has been asked so many Times. But I have Confusion Among those. I have tried this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
Where cell is object of UITableviewCell, But There is Not any Type of Notification. I know there is a little Bug , please help me to find out.
Place the last line as [[UIApplication sharedApplication] scheduleLocalNotification:reminderNote]; after reminderNote.fireDate line.
log the reminderNote.fireDate and check the format.
Hope this helps.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[cell.btn backgroundImageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[cell.btn setBackgroundImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
UILocalNotification *reminderNote =[[UILocalNotification alloc]init];
reminderNote.soundName = #"music.mp3";
reminderNote.alertBody = #"Wish birthday to :%#",[kAppDelegate.commString objectAtIndex:indexPath.row];
NSString *date =[kAppDelegate.String objectAtIndex:indexPath.row];
NSDate *dateP = [ dateformat dateFromString:date];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dateP];
[components setHour:4];
[components setMinute:59];
[components setSecond:10];
reminderNote.fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
[[UIApplication sharedApplication] scheduleLocalNotification:reminderNote];
}
You can add the local notifications upto 64 at single time.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSDate *newDate = [fireDate dateByAddingTimeInterval:(6*60*60)];
// 6*60*60=6 hour*60 minutes*60 seconds
// [fireDate dateByAddingTimeInterval:(6*60*60*i)];
localNotification.fireDate = newDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = 0;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
if(soundfileName == nil)
{
localNotification.soundName = UILocalNotificationDefaultSoundName;
}
else
{
localNotification.soundName = soundfileName;
}
localNotification.alertLaunchImage = launchImage;
localNotification.applicationIconBadgeNumber = 1;
localNotification.userInfo = userInfo;
// NSLog(#"%#", [localNotification description]);
// Schedule it with the app
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
If you want to keep all the objects of NSNotification, then you need to store that somewhere. i.e in Array.
You can also use following methods for NSNotifications operation.
- (void)cancelLocalNotification:(UILocalNotification *)notification
- (void)cancelAllLocalNotifications
Make sure you are receiving notifications on
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
As a good practice prior to use the object, make sure you have initialized and set all the values to particular object.
please try this for local notification
-(void)localnotification{
NSDate *pickerDate = [self.datepicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.labelname.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

Can't schedule an UILocalNotification x days from now

I've been trying now for way too many hours without finding the problem/solution. this code is supposed to schedule a notification x days from now by comparing wd(the selected weekday) and item.itemDayName(Int of the current weekday). Right now the code only works when wd == 7, as wd == 7 --> all weekdays are selected (wd 0-6 = sun-sat). I will appreciate any feedback given, thank you.
- (void)scheduleNotificationWithItem:(ToDoItem *)item andWeekday:(int)wd{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
if (wd < 7) {
[dateComps setYear:item.itemYear];
[dateComps setMonth:item.itemMonth];
if (item.itemDayName != (wd + 1)) {
int result = (wd + 1) - item.itemDayName;
result = result + item.itemDay;
[dateComps setDay:result];
}
else{
[dateComps setDay:item.itemDay];
}
}
else {
[dateComps setYear:item.itemYear];
[dateComps setMonth:item.itemMonth];
[dateComps setDay:item.itemDay];
}
[dateComps setHour:item.itemHour];
[dateComps setMinute:item.itemMinute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
//localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(1*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
if (wd < 7) {
[localNotif setRepeatInterval: NSCalendarUnitWeekOfMonth];
}
else {
[localNotif setRepeatInterval: NSCalendarUnitDay]; //Repeat daily
}
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"Time to take %#!", nil),
item.itemName];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.alertTitle = NSLocalizedString(#"Piller", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.itemName forKey:item.itemKeyName];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}

How to create ios LocalNotification from array of dates?

I have an array of dates
NSArray *datesArray=[NSArray arrayWithObjects: #"2014-09-14 00:00:00",#"2014-08-21 07:12:36",#"2014-08-14 00:00:00",#"2014-07-14 00:00:00",#"2014-06-14 00:00:00",#"2015-01-01 10:00:00",#"2014-06-14 00:00:00",#"2014-05-14 11:24:15", nil];
now i want to fire one day before the date available in array
How to implement it?
I was trying this
NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
[Formatter1 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
[Formatter1 setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[Formatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDate *date1 =[NSDate date];
NSString *string =[Formatter1 stringFromDate:date1];
NSLog(#"sring %#",string);
NSDate *todaydate =[Formatter1 dateFromString:string];
NSLog(#"2day date is %#",todaydate);
for (int i=0;i<datesArray.count;i++)
{
NSDate *_date =[Formatter1 dateFromString:[datesArray objectAtIndex:i ]];
NSLog(#"date is %#",_date);
if(_date == todaydate){
localNotif.fireDate = _date;
localNotif.alertBody = #"festival";
localNotif.alertAction=#"Show me";
localNotif.applicationIconBadgeNumber = 1;
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
You can subtract a day by using the NSCalendar functions, specifically dateByAddingComponents
NSArray *datesArray = #[#"2014-09-14 00:00:00",#"2014-08-21 07:12:36",#"2014-08-14 00:00:00",#"2014-07-14 00:00:00",#"2014-06-14 00:00:00",#"2015-01-01 10:00:00",#"2014-06-14 00:00:00",#"2014-05-14 11:24:15"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-1];
NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
[Formatter1 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
[Formatter1 setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[Formatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [calendar dateByAddingComponents:dateComponents toDate:[Formatter1 dateFromString:obj] options:0];
localNotif.alertBody = #"festival";
localNotif.alertAction = #"Show me";
localNotif.applicationIconBadgeNumber = 1;
localNotif.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}];
W

A few questions about NSLocalNotifications

This is my localNotification codes.
NSDate *currentDate = [NSDate date];
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:currentDate];
[components setTimeZone:[NSTimeZone systemTimeZone]];
[components setHour:13];
[components setMinute:11];
[components setDay: sonOdemeGunuNumber.integerValue -3];
NSDate *test = [calendar dateFromComponents:components];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = test;
localNotification.alertBody = [NSString stringWithFormat:#"%# 3 days left.",_txtBankaAdi.text];
localNotification.alertAction = #"Show item";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
localNotification.repeatInterval = kCFCalendarUnitDay;
localNotification.repeatInterval = kCFCalendarUnitMonth;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
sonOdemeGunuNumber is ToDoItem alert day(number of current day for example -3).
if(sonOdemeGunuNumber.integerValue == currentDay.integerValue){
localNotification.repeatInterval = nil; }
I wanted to notify user 3 days earlier and it should continue get alert until currentDay = sonOdemeGunuNumber.
1- If I write this if-else statement it will work ?
2- If user delete the localNotification Item in my TableView, in this case item is Bank Account ?
Bank Account localNotification will delete itself automatically ?
Thank you !
Have a nice day everyone...
I found the solution for if user delete the item in tableview i cancel deleted item's localNotification..
First of all, send ID with userInfo to the LocalNotification Center.
localNotification.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:_txtItemName.text,#"delThisNot", nil];
Secondly go and edit your tableView method.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
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 *adi = [[self.fetchedResultsController objectAtIndexPath:indexPath]valueForKey:#"odemeAdi"];
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"delThisNot"]];
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
}
}
adi = Deleting item.
uid = your item id (which is your txtItemName.text)
if ([uid isEqualToString:adi])
{
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
break;
}
if user want to delete item name (adi) == uid (txtItemName.Text)
Cancel this notification.
Sorry for my grammers I just wanted to help other people I hope you guys can understand me :D
Thanks.

Location Notification matching current date to date of object

I have several objects inside an array, each object has it's own date.
I want to fire a local notification whenever the the current date == object date.
I have some code, i would like someone to tell me if it makes sense and if it should work, i have taken care of the delegates and reloadData method.
Here is the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"LiveIdent";
LiveViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
LiveMatchObject *item = [tableDataLiveMatch objectAtIndex:(int)([indexPath row]/2)];
if ([item isKindOfClass:[LiveMatchObject class]]) {
NSString * dateString = [NSString stringWithFormat: #"%#",item.matchDate];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"'Hoje ás' HH:mm 'horas"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
//// starts here the notification code
// create a timer to keep track of the current date
NSDate *now = [NSDate date];
NSDateFormatter *daterFormatter = [[NSDateFormatter alloc] init];
[daterFormatter setTimeZone:[NSTimeZone systemTimeZone]];
// if current date = date stored in the object then do this
if (myDate == now){
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = myDate;
localNotification.alertBody = #"Início da partida";
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
}
NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *localNotification = [localNotifications objectAtIndex:indexPath.row];
[cell.textLabel setText:localNotification.alertBody];
[cell.detailTextLabel setText:[localNotification.fireDate description]];
return cell;
}
Should this work or this is a total disaster?
P.S - i cannot test, because i reads from live events which actually will occur tomorrow, so i'll have to wait, to see it for myself.
Thank you.
Yes your code is looking good but you can test your local-notification by setting some near time instead of waiting for tomorrow here is the code which I used in my project:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay: 16];
[components setMonth: 3];
[components setYear: 2014];
[components setHour: 10];
[components setMinute:32];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];
Hope this will helps you.

Resources