I wrote an app that allows the user to enter data in a UITextField, and one of them allows them to enter in a specific date. I'm trying to have an alert appear in the iPhones Notification Center when the date is 15 hours away, even when the app is not running at all.
EDIT: New code-
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMdd"];
NSDate *eventDate=[dateFormatter dateFromString:eventDateField.text];
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-15*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = #"Event Tomorrow!";
localNotif.alertAction = #"Show me";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];
}
Youre trying to send the message dateByAddingTimeInterval: to whom? Nobody. You need a receiver for the message, an object that can then run the method.
[[NSDate date] dateByAddingTimeInterval: -20*60];
(NSDate date is the current date and time).
Store the date obtained from the text field in a NSDate object, eventDate. You will want to set the date with time also. The reason you are getting that error is that dateByAddingTimeInterval: should be called on an NSDate object and is not an identifier in itself. Set the fireDate of your local notification as
localNotif.fireDate=[eventDate dateByAddingTimeInterval:-15*60*60];
This will return a date which is 15 hours before the event.
EDIT: You need to create an NSDateFormatter object and set its format to how it is stored in meetingDateField. Then use the dateFromString: to get the NSDate from the text field.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm'/'dd'/'yyyy"];
NSDate *eventDate=[dateFormatter dateFromString:meetingDateField.text];
In order to call [-dateByAddingTimeInterval:], you must have an NSDate object. In your code above, you don't. It should look something like:
NSDate* now = [NSDate date];
localNotif.fireDate = [now dateByAddingTimeInterval:20*60];
Related
I'm having prob,when i open the app i can see the latest result,when i swipe left of the uiview i can see the previous result,the problem that i face i wanted to swipe right to come for the latest result again.
the is the code for swipe left
-(void)swipeLeft
{
NSLog(#"Mag Date:%#",magCurDate);
NSDate *tempDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
tempDate = [formatter dateFromString:magCurDate];
NSLog(#"temp Date:%#",tempDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-1];
[dateComponents setHour:8];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:tempDate options:0];
NSLog(#"target Date:%#",targetDate);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"ddMMYYYY"];
NSString *sDate = [df stringFromDate:targetDate];
NSLog(#"sDate Date:%#",sDate);
[self LoadMagnumResult:sDate];
}
this is my swipe right code,but i couldn't stop on the latest result,i want the last swipe to be the latest result.
-(void)swipeRight
{
NSLog(#"Mag Date:%#",magCurDate);
NSDate *tempDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
tempDate = [formatter dateFromString:magCurDate];
NSLog(#"temp Date:%#",tempDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:+1];
[dateComponents setHour:8];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:tempDate options:0];
NSLog(#"target Date:%#",targetDate);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"ddMMYYYY"];
NSString *sDate = [df stringFromDate:targetDate];
NSLog(#"sDate Date:%#",sDate);
[self LoadMagnumResult:sDate];
}
I'm assuming that the latest result cannot be in the future. In other words, the max date for "latest result" is today. I'm also assuming that a left swipe should increment the information until today is reached. If you want a left swipe to jump to today, then the code is even easier. Let me know if that's what you meant. Since I don't have your application, I just made an internal variable that stored a date called testDate. I also put a label on screen and called it outputLabel. You can modify the code to fit your needs.
Finally, I changed the methods to make the right swipe go back in time and the left swipe go forward in time. A user is already used to thinking of a right swipe as going backwards (back on a web browser, etc). Remember a right swipe starts on the left and ends on the right.
First, I would build a helper method to turn dates into strings:
- (NSString*)stringFromDate:(NSDate*)date
{
//Helper method to return a string from a date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yy"];
return [formatter stringFromDate:date];
}
This is my right swipe method. Notice how I use time intervals to increment dates. That can save you a few lines of code from your methods. Unless I'm wrong, it looks like you are trying to increment the date by 24 hours for each swipe. I also made a constant before these two methods so you don't have to search through your code if you want to change the days to increment per swipe.
#define kDaysPerSwipe 1
- (void)swipeRight:(UISwipeGestureRecognizer*)swipeRight
{
NSLog(#"right swipe received");
//Number of days to add
int numberOfDaysToAdd = kDaysPerSwipe;
//Generate a new date
NSDate *newDate = [self.testDate dateByAddingTimeInterval:-(60*60*24*numberOfDaysToAdd)];
//Store the new date
self.testDate = newDate;
//Output the new date
self.outputLabel.text = [self stringFromDate:self.testDate];
}
Here is my left swipe method. Notice how I compare the newDate to today and then only store the EARLIER date of the two before proceeding.
- (void)swipeLeft:(UISwipeGestureRecognizer*)swipeLeft
{
NSLog(#"left swipe received");
//Number of days to add
int numberOfDaysToAdd = kDaysPerSwipe;
//Generate a new date
NSDate *newDate = [self.testDate dateByAddingTimeInterval:(60*60*24*numberOfDaysToAdd)];
NSLog(#"newDate: %#", [self stringFromDate:newDate]);
//Compare newDate to today. Return whichever is earlier.
newDate = [[NSDate date] earlierDate:newDate];
self.testDate = newDate;
//Show the output on the screen
self.outputLabel.text = [self stringFromDate:self.testDate];
}
I'm having issues when trying to schedule a UILocalNotification using the following code:
- (IBAction) createNotification {
//Just to verify button called the method
NSLog(#"createNotification");
NSString *dateString = dateTextField.text;
NSString *textString = textTextField.text;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy HH:mm"];
[formatter setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *alertTime = [formatter dateFromString:dateString];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
if(notification){
notification.fireDate = alertTime;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = 0;
notification.alertBody = textString;
[app scheduleLocalNotification:notification];
NSLog(#"%#", dateString);
}
}
The code is being called correctly when I press the button and I'm passing in the following date string:
02-12-2012 19:01
I've also tried
02/12/2012 19:01
to no avail. (I change the time accordingly depending on the time of testing e.g. 21:06)
Can someone please explain why the local notification isn't displaying?
Thanks in advance,
Jack
Local notifications are delivered, but do not display (i.e., no badges, no sounds, no alerts) when the app is running and in the foreground. But the application:didReceiveLocalNotification: method of your app delegate is called, if you need to react to a local notification in some way.
See the UILocalNotification class reference for details.
I am using UIDatePicker in my app and when i take the date that was chosen with:
NSDate *date = picker.date;
picker.date returned the day before the date that I chose.
any idea why it happens?
UIDatePicker will be displaying dates and times in your local timezone. However, NSDate does not have any concept of a timezone as it stores an absolute number of seconds since a reference date. When NSLogging a date, it shows the date and time in GMT. I expect if you work out your local timezone difference from GMT, you will see that it is the correct date.
Try creating an NSDateFormatter or NSCalendar with the appropriate locale and pass the date through that.
For further reading on this common topic, see this site written by another SO contributor.
give this a try worked for me
NSDate* sourceDate = [NSDate date];
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] autorelease];
//i'm outputting mine in a label you can use anything you like
NSString *dateOutput = [[[NSString alloc] initWithFormat:#"%#", destinationDate]autorelease];
self.dateLabel.text = dateOutput;
Remember to create the NSDate and then output it with a valid timezone and calendar!
NSDate only represents an absolute point in time. It has no concept of timezone (NY, Barcelona, ...) or calendar (Gregorian, Hebrew, ...).
UIDatePicker returns by default a NSDate with the system NSCalendar and NSTimeZone, but when you try to print it later, you do not format the output. You may have there the mismatch.
So 1st you need to setup the UIDatePicker correctly and 2nd transform the output with the NSDateFormatter so it knows the Calendar and the TimeZone being used.
An example code with the init of the UIDatePicker and then printing the result:
- (void)viewDidLoad
{
[super viewDidLoad];
// init the UIDatePicker with your values
// by default UIDatePicker inits with today, system calendar and timezone
// Only for teaching purposes I will init with default values
NSDate * now = [[NSDate alloc] init];
[_datePicker setDate: now]
animated: YES];
_datePicker.timeZone = [NSTimeZone localTimeZone];
_datePicker.calendar = [NSCalendar currentCalendar];
[_datePicker addTarget: self
action: #selector(getDatePickerSelection:)
forControlEvents:UIControlEventValueChanged];
}
-(void)getDatePickerSelection:(id) sender
{
// NSDateFormatter automatically inits with system calendar and timezone
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Setup an output style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
// Medium style date, short style time => "Nov 23, 1937 3:30pm"
NSString *dateString = [dateFormatter stringFromDate:date];
}
Check the answer I did for another very similar question:
NSDate output using NSDateFormatter
Did you check the timezone?
When you print an NSDate it will use GMT as it timezone.
If you set the system timezone to the NSDateFormatter you might get an other date, because it will take the timezone and calculate the time accordingly.
Add this code and see if the output is correct:
NSDate *date = picker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSLog(#"Date: %#", [dateFormmater stringFromDate:date]);
[dateFormatter release], dateFormatter = nil;
Just add one line of code
self.datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
0 is for GMT 00 . Add according to your time zone.
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr];
[Dateformat setDateFormat:#"HH:MM"];
NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
Place a scheduled timer in your uiview did show (or did load) method:
[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
target:self
selector:#selector(updateTime:)
userInfo:nil
repeats:YES];
Then, put this method in your View Controller:
- (void) updateTime:(id)sender
{
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY HH:mm:SS"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer. I didn't check this for bugs.
}
This will call the "updateTime:" method once a second, updating your controller.
[NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.
You have a bug in your code:
Instead of
[Dateformat setDateFormat:#"HH:MM"];
it should be
[Dateformat setTimeFormat:#"HH:MM"];
I have the following code which is used to take the time of one NSDate and the current date and combine them into one NSDate. However the formatters are set correctly, but it's returning a date that isn't even close to the one it should be. Here is the code
/* Get the current date and make a formatter to just show the date ONLY */
NSDate *currentDate = [NSDate date];
NSDateFormatter *curDateFormatter = [[NSDateFormatter alloc] init];
[curDateFormatter setDateFormat:#"MM/dd/YYYY"];
/* Create a formatter for the time ONLY */
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm"];
/* Create a formatter for both date and time */
NSDateFormatter *combinedFormatter = [[NSDateFormatter alloc] init];
[combinedFormatter setDateFormat:#"MM/dd/YYYY hh:mm"];
NSString *combinedDateTime = [NSString stringWithFormat:#"%# %#", [curDateFormatter stringFromDate:currentDate], [timeFormatter stringFromDate:time]];
NSDate *combinedDate = [combinedFormatter dateFromString:combinedDateTime];
/* release the formatters */
[curDateFormatter release];
[timeFormatter release];
[combinedFormatter release];
return combinedDate;
Say it is doing it when this message was posted, it should have 11/10/2010 06:47 but instead it's like 12/27/2009 11:45. Does this in the simulator and the device.
Instead of using the combinedDateFormatter, try the following:
NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime];
This worked fine for me.
Value for combinedDateTime string was 09/27/2011 11:55
Value for combinedDate date object was 2011-09-27 11:55:00 +0530
Take a look at below URL;
Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds