I use touchbegin function like
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
touchStartTime = [event timestamp];
NSLog(#"Time of touch is %f ", touchStartTime);
}
but I would like to compare it with
double timeToCompare = [[NSDate date] timeIntervalSince1970];
but the format is not compatible (timestamp has some other reference point). How do I convert [event timestamp] to normal NSDate or vice versa?
As [event timestamp] is related to the system up time, you can get the [NSProcessInfo systemUptime] and get the current system time at the same time and go from there.
[[NSDate date] timeIntervalSince1970] - [NSProcessInfo systemUptime] + [event timestamp] == [compareDate timeIntervalSince1970]
(Well, I don't sign this in blood. Never tried it myself.)
Given that [UIEvent timestamp] is the number of seconds since the system was started, one approach to record the first event's timestamp and use that as a reference.
#interface MyClass ()
{
BOOL _haveFirstTimestamp;
NSTimeInterval _firstTimestamp;
NSTimeInterval _firstTimestampTime;
}
#end
...
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
NSTimeInterval timestamp = [event timestamp];
if (!_haveFirstTimestamp) {
_haveFirstTimestamp = YES;
_firstTimestamp = timestamp;
_firstTimestampTime = [[NSDate date] timeIntervalSince1970];
}
NSTimestamp timeSince1970 = timestamp - _firstTimestamp + _firstTimestampTime;
NSLog(#"Time of touch is %f ", timeSince1970);
}
Related
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"];
}
Im trying to load an events(data) (from json file) that matches today's date into my tableView when the today's button is pressed then only the data with today's date will be loaded there and when the future button is pressed the events with later dates will be loaded, the only problem I have here is when i run my program nothing is actually happening when I press in either of these UIbuttons, I got all the events regardless their date and without even clicking on any UIButton, u can see below some of my code, it would be great if someone could figure out what is the problem there and since Im not quiet sure about how to use predicate to filter the data:
#property (strong, nonatomic) NSArray *dateEvents;
#end
#implementation HomeViewController {
NSArray *_events;
NSArray *_dateEvents;
}
- (IBAction)upcomingEvents:(id)sender {
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"mama");
_dateEvents = [_events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Events * event, NSDictionary *bindings){
return [event.date isEqualToString:dateString];
}]];
self.myTableView.dataSource = self;
[self.myTableView reloadData];
NSLog(#"yes");
}
Thanks,
I'm not sure this will definitely help, because I can't see enough code so be certain that this is your problem, but you might find it useful to convert all the dates to NSDate objects (so that you can be certain that the problem is NOT that the strings are actually not equal), and then check whether the day is the current day, or not, by using this category method on NSDate:
NSDate+Extensions.m:
static NSCalendar* ___calendar;
#implementation NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:self];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
-(NSCalendar*)currentCalendar
{
if(___calendar == nil)
{
___calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
}
return ___calendar;
}
#end
NSDate+Extensions.h
#interface NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date;
#end
I have a "Today" button to reset a datePicker to today's date. This works for the current month, but not for other months.
The method is:
- (IBAction)setToday:(id)sender
{
NSLog(#"%s", __FUNCTION__);
[datePicker setDateValue:[NSDate date]];
[datePicker setNeedsDisplay: YES];
}
What am I doing wrong?
I'm assuming your date picker is a property, in which case you should use the self keyword.
self.datePicker.date = [NSDate date];
I have this method:
- (void) receivedData {
}
This should run about every 50 to 100 milliseconds. Is there a way to check the time since the last time it was called and print the last time to an NSString?
#interface MyClass() {
NSDate* receivedDataTimestamp;
....
}
...
-(void)receivedData {
NSDate* now = [NSDate date];
if (receivedDataTimestamp != nil) {
NSTimeInterval delta = [now timeIntervalSinceDate:receivedDataTimestamp];
NSLog(#"%f seconds since recevedData was called last", delta);
}
receivedDataTimestamp = now;
....
}
I added this code which functions as an auto timeout in my app. The userDefaults doubleForKey:#"timeoutLength" should be in minutes. For example, if value is 500, that should mean 500 minutes.
I keep seeming to be hitting the timout loop though even when it hasn't really been 500 + min. Is anything wrong in my code? Perhaps a minutes/seconds error etc.
[userDefaults setDouble:[[userContextDictionary valueForKey:#"autologout_idle_timeout"] doubleValue] forKey:#"timeoutLength"];
double timeDifference = ([[NSDate date] timeIntervalSince1970] - [userDefaults doubleForKey:#"Close Time"]) / 60;
if (timeDifference > [userDefaults doubleForKey:#"timeoutLength"]) {
NSLog(#"Timeout Hit");
} else {
NSLog(#"No Timeout");
}
Edit:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[userDefaults setObject:[NSDate date] forKey:#"Close Time"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[userDefaults setDouble:[[userContextDictionary valueForKey:#"autologout_idle_timeout"] doubleValue] forKey:#"timeoutLength"];
//This is an int like 500, or 600, etc.
NSDate *closeDate = [userDefaults objectForKey:#"Close Time"]
NSTimeInterval timeWhenClosedTimeInterval = [closeDate timeIntervalSince1970];
NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval timeDifference = ((todayTimeInterval - timeWhenClosedTimeInterval ) / 60);
if (timeDifference > [userDefaults doubleForKey:#"timeoutLength"]) {
NSLog(#"Timeout Hit");
} else {
NSLog(#"No Timeout");
}
return YES;
}
NSTimeInterval is expressed in seconds, not minutes.
Here's the Apple doc where it's described.
I'm not 100% certain what your ultimate problem with, but 500 seconds doesn't seem like nearly enough time.
In the meantime, I wrote up some changes to your code to demo for myself:
NSDate * yesterday = [[NSDate date] dateByAddingTimeInterval: (-1 * 60 * 60 * 24 )];
NSTimeInterval yesterdayTimeInterval = [yesterday timeIntervalSince1970];
NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];
// this properly converts timeDifference in seconds to minutes
NSTimeInterval timeDifference = ((todayTimeInterval - yesterdayTimeInterval ) / 60);
NSLog( #"time difference is %4.2f", timeDifference );
which came up with 1400 minutes (divided by 60 minutes per hour = 24 hours).
My guess is there is some error with setting the NSUserDefaults values, or an error with your timeDifference calculation. Add this line and make sure you are actually setting the timeout length to 500:
NSLog(#"Timeout length: %f, close time: %f, time difference: %f", [userDefaults doubleForKey:#"timeoutLength"], [userDefaults doubleForKey:#"Close Time"], timeDifference);