calculating 'timeIntervalSinceNow' with a negative value (CLLocation example)?
Asked Answered
A

2

6

i don't understand this example from the doc : the timeIntervalSinceNow method should show a positive value, but how can we reach "5" as mentioned in the code? (i think it's either 0 more or less, or -10 , -20, -30 etc... but how can we get a positive value such as 5?) :

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;

Thanks for your help

Achelous answered 3/4, 2012 at 1:56 Comment(0)
A
11

If the result of the timeIntervalSinceNow call is negative (meaning that the timestamp is in the past (which, in this case, it always will be)) it will be converted to a positive number. -2.5 would become +2.5, for example (and vice versa).

Then you test the inverted-sign value, to see if it is greater than 5.0 -- in this case, that means the timestamp is from more than five seconds ago. If it is, you do nothing with the location data, because it's too old to be useful.

Personally, I would have written this without the sign inversion, using a negative number in the test:

 if( [[newLocation timestamp] timeIntervalSinceNow] < -5.0 ) return;
Atthia answered 3/4, 2012 at 3:3 Comment(4)
thanks Iulius Cæsar, how would you force cllocation to send always the new location instead of the cached one? (not just let the app do nothing in case the value is cached, but tell the app: "if you've got a cached value, restart cllocation" ?)Achelous
You can't; it will send you a new one as soon as it possibly can. All you can do it wait for it.Atthia
thanks, i can't find out the amount of time of the cache by default? do you know something about it?Achelous
The location hardware takes a lot of power, so it only runs when requested to. When it shuts down, it keeps a record of the last known location, because there's no reason not to. When it starts up again, the first CLLocation it has is that recorded value. The only way to find out how old it is is to check its timestamp.Atthia
S
3

That is what NSDate documentation have to say about timeIntervalSinceNow:

The interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative.

In this case timestamp was recorded in the past, and it will always be earlier than 'now'. If, on the other hand, you would use timeIntervalSince1970, the result would be positive.

Samoyedic answered 3/4, 2012 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.