UILocalnotification is not firing - objective-c

Since i just cant get a good answer for this and spend so much time on this, i will ask my question in details
All i want is to create an alarm according to date picker.
setting alarm to 10 seconds from now, is works great .
UIDatePicker, is works (print the date-but not the date i have picked, but 3 hours later)
i know there is an issue with local times, but i just cant find any good explanation.
my propose, and i guess that almost everyone,is not getting involve in local times, but to take each user's clock, and set alarm according to his time.
my code, is not working, i dont know why. its not firing(only if i set it to 10 seconds later)
please, i know that time zone should be different or something, but if you can explain what exactly to do and how, that would be great . thanks.
this is the code :
-(void)setDatePicker
{
CGRect pickerFrame = CGRectMake(0,265,0,0);
UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
[myPicker addTarget:self action:#selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];
[[[CCDirector sharedDirector] view] addSubview:myPicker];
[myPicker release];
}
-(void)pickerChanged:(UIDatePicker*) datePicker
{
date=datePicker.date;
NSLog(#"value: %#",date);
}
and the local notification :
-(void) scheduleNotificationForDate: (NSDate*)theDate
{
/* Here we cancel all previously scheduled notifications */
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
//[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
//NSDate *notificationDate = [dateFormat stringFromDate:theDate];
localNotification.fireDate = theDate;
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);
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

i got it .
i had to change the format and it worked.
nothing that relates to zones.
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormat stringFromDate:date];
NSDate *notificationDate = [dateFormat dateFromString:dateString];
localNotification.fireDate = notificationDate;

Related

Working with Date and Time separately using NSDatePickerView on Xcode

I have a part of app that set date and time of an appointment. For this, I have two NSDatePickerView. The first one I set to NSDatePickerModeDate, while the other one to NSDatePickerModeTime. But actually they should be referring to a same NSDate object inside a NSMutableDictionary entry. I know about NSDatePickerModeDateTime, but I need the date and time to be picked separatedly.
I know how to set up the NSDatePickerView to show and hide and event control and such, but at the event control UIControlEventValueChanged fire for NSDatePickerView, I'm confused on how to code the change for this, and also how to initialise the pickers (datePicker.date = today, timePicker.date = "9:00 AM")
#interface MyViewController () {
NSMutableDictionary *data;
}
#end
#implementation MyViewController
#synthesize datePicker, timePicker;
- (void) viewDidLoad {
[super viewDidLoad];
data = [[NSMutableDictionary alloc] init];
[data setObject:[NSDate date] forKey:#"date"];
datePicker.datePickerMode = UIDatePickerModeDate;
timePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:#selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[timePicker addTarget:self action:#selector(changeTime:) forControlEvents:UIControlEventValueChanged];
datePicker.date = data[#"date"]; //????
timePicker.date = data[#"date"]; //????
}
- (IBAction) changeDate:(id)sender {
UIDatePickerView *dp = (UIDatePickerView *)sender;
[data setObject:dp.date forKey:#"date"]; //????
}
- (IBAction) changeTime:(id)sender {
UIDatePickerView *tp = (UIDatePickerView *)sender;
[data setObject:tp.date forKey:#"date"]; //????
}
The part that I don't know how to code it is denoted by //????. I've read about NSDateFormatter, NSCalendar, and some kind of date components on some answers, but that was actually making me more confused as it also throws strings and structs into the mix, what to use to do what and when. Please help.
You can set both date pickers to the same date and time. The unused part is there but it isn't displayed and can't be changed. When the user changes the value of one date picker you have to set the other date picker to the same value.
- (IBAction)changeDate:(id)sender {
NSDatePicker *dp = (NSDatePicker *)sender;
[data setObject:dp.dateValue forKey:#"date"];
self.timePicker.dateValue = dp.dateValue;
}
- (IBAction)changeTime:(id)sender {
NSDatePicker *tp = (NSDatePicker *)sender;
[data setObject:tp.dateValue forKey:#"date"];
self.datePicker.dateValue = tp.dateValue;
}
u can try this
///Convert Full date to only date
- (IBAction) changeDate:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"date"];
}
///convert Date to only time format
- (IBAction) changeTime:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"Time"];
}

"NSDate not an Objective-C object" error shows when run the application in IOS 7 in real device

NSDate object is working for iPhone, iPad when i ran the application in real devices. But when I run the application in iPad real device than it gives <not an Objective-C object> error. I tried to sort out it. but couldn't.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}
- (NSDate*) getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
int startPos = [dateString rangeOfString:#"("].location+1;
int endPos = [dateString rangeOfString:#")"].location;
NSRange range = NSMakeRange(startPos,endPos-startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSTimeInterval interval = milliseconds/1000;
return [NSDate dateWithTimeIntervalSince1970:interval];
}
because of this issue i initialize the NSDate object and saw the date value. (NSDate *_Date = [NSDate alloc] init];) in here also gives same error? why is that? anyone faced this error ??
First off you can just remove this line:
NSDate *_Date = [NSDate alloc] init];
Since the next line just redeclares it, also you in the line you should remove you are missing a [.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
// Not needed since the line after it also declares the variable.
//NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}

DatePicker not selecting the correct date

I have a Button in my view.On tapping the Button you get a datepicker which defaults to today's date, the user can then select the date they want to search for events.
The problem is, no matter what date I select, it always returns the current day and adds this to my TextField which i have placed inside mu Button.Can any one tell me where I am wrong.am setting the date picker programatically.
Below is my code hopefully someone can help me out!
//displaying date picker while clicking on button
- (IBAction)startDateButtonAction:(id)sender
{
if ([popOverController isPopoverVisible]) {
[popOverController dismissPopoverAnimated:YES];
}
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController
UIView *popoverView1 = [[UIView alloc] init]; //view
datePicker =[[UIDatePicker alloc]init];//Date picker
datePicker.frame =CGRectMake(0,0,240, 150);
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setMaximumDate:[[NSDate date] dateByAddingTimeInterval:24*60*60*-6]];
[datePicker setMinimumDate:[DateFormatter getSubtractedDateForomCurrentDateWith:35]];
datePicker.date = [DateFormatter getDateFromString:startDateLabel.text];
datePicker.selected = YES;
[datePicker addTarget:self action:#selector(datePickerValue) forControlEvents:UIControlEventValueChanged];
[popoverView1 addSubview:datePicker];
popoverContent.view = popoverView1;
popOverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
[popOverController setPopoverContentSize:CGSizeMake(240, 150) animated:NO];
[popOverController presentPopoverFromRect:startDateButton.frame inView:headerView permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
//action function while selecting any of the date from date picker
- (void) datePickerValue
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-6];
NSDate *labelStartDate = datePicker.date;
startDate = [DateFormatter getOnlyDateComponentsFromDate:labelStartDate];
NSDate *labelEndDate = [self addDayToDate:startDate Number:6];
startDateLabel.text = [DateFormatter getDateStringddmmyyy:labelStartDate];
endDateLabel.text = [DateFormatter getDateStringddmmyyy:labelEndDate];
}
[including the functions that am used here]
//used for getting date components
+(NSDate *) getOnlyDateComponentsFromDate:(NSDate *)date
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
return dateOnly;
}
- (NSDate *) addDayToDate:(NSDate *)date Number:(int) number
{
NSDate *newDate = [date dateByAddingTimeInterval:60*60*24*number];
return newDate;
}
Iam using ARC.
here datePicker.date gives me only the current date even though I select any other dates
I found out my mistake at last..The problem was with my code where i set the maximum and minimum value for the datePicker.removing the code for setting maximum and minimum value the code works fine..
You need to initialise your datepicker like this.
_datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
_datePicker.tag=1951;
_datePicker.datePickerMode=UIDatePickerModeDate;
[_datePicker addTarget:self action:#selector(ageChanged:) forControlEvents:UIControlEventValueChanged];
[_actionSheet addSubview:_datePicker];
And for your this method: ageChanged:
-(void)ageChanged:(id)sender {
NSDate *datePicked = [_datePicker date];
NSLog(#"%#", datePicked);
formattedDate = [dateFormatter stringFromDate:datePicked];
}
and set dateFormatter as per your requirement.
while changing your date it will give you the date you have selected in date Picker.
I hope this will help you for date picker.

ios how to change an image at specific time

I have an image that i want to display as a sun during daytime i.e. from 6am to 6pm, and moon from 6pm to 6am.
I have successfully implemented that but the problem is the image would not change when it reaches the specified time unless re-run the apps before the image change itself.
I don't want to use NSTimer to check the time, like every second. The only possible solution i think of is using NSLocalNotification but I'm a newbiew to it. any help? =)
-(void) dayOrNight
{
NSDate* date = [NSDate date];
NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HHmm"];
NSString* dateString = [dateFormat stringFromDate:date];
NSNumber* currentTime = [NSNumber numberWithInt:[dateString intValue]];
NSNumber* daytime = [NSNumber numberWithInt:600];
NSNumber* nightime = [NSNumber numberWithInt:1800];
NSLog(#"current time: %#",dateString);
dayNight = [[UIImageView alloc] initWithFrame:CGRectMake(265, 10, 50, 50)];
if ( [currentTime doubleValue] >= [daytime doubleValue] && [currentTime doubleValue] <= [nightime doubleValue] )
{
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
else
{
dayNight.image = [UIImage imageNamed:#"moon.png"];
}
[self.view addSubview:dayNight];
}
Local notification should be fine, I guess.
Here you can get all needed code snippets to implement execution of dayOrNight method at needed time. Also, you shouldn't add new view every time you change the picture.
I think it is impossible to do without NSTimer. U can set refreshTime by yourself (for example 1 min/ if u don`t want to do it every second)))
Or u can call this method in other methods, which are working in your class every time...
maybe u have some object, which u use during your class is working...
-(IBAction)myButtonWhichIPressDuringIworkHere {
///some actions
[self dayOrNight];
}
In other case you should to use NSTimer
you don't need to check the time at every second.
this is one of the possible solutions. it has been tested on real device only.
your UIYourViewController.m
- (void)viewWillAppear:(BOOL)animated {
NSDate *_currentDate = [NSDate date];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00AM +0000'"]; // set the morning date here
NSString *_morningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00PM +0000'"]; // set the evening date here
NSString *_eveningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd hh:mma zzz"];
NSDate *_morningDate = [_dateFormatter dateFromString:_morningDateString];
NSDate *_eveningDate = [_dateFormatter dateFromString:_eveningDateString];
NSTimeInterval _intervalToMorningDate = [_morningDate timeIntervalSinceDate:_currentDate];
NSTimeInterval _intervalToEveningDate = [_eveningDate timeIntervalSinceDate:_currentDate];
if (_intervalToMorningDate > 0) {
// now it is night
dayNight.image = [UIImage imageNamed:#"moon.png"];
[self performSelector:#selector(replaceTheBackgoundForMorning) withObject:nil afterDelay:_intervalToMorningDate];
} else {
// now it is daytime
dayNight.image = [UIImage imageNamed:#"Sun.png"];
[self performSelector:#selector(replaceTheBackgoundForEvening) withObject:nil afterDelay:_intervalToEveningDate];
}
}
- (void)viewDidDisappear:(BOOL)animated {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
and finally you should add them to your same .m file:
-(void)replaceTheBackgoundForMorning {
// reaplce the backgound here
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
- (void)replaceTheBackgoundForEvening {
// reaplce the backgoung here
dayNight.image = [UIImage imageNamed:#"moon.png"];
}

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.