CLLocationmanager gets stuck sometimes - iphone

I'm working on an application which periodically obtains the user's location. The big problem is that sometimes the app gets stuck, no more updates are delivered. Even if I (kill and) restart my app, nothing changes. (The accuracy values set for location manager are near 100-200 meters.)
BUT, when I start the Google Maps App, in a few seconds it gets a very accurate location (which is delivered to my app to if I switch back). Why ?
Here are some relevant code parts :
The timerFiredAction is called periodically by the timer.
-(void) timerFiredAction
{
if (isStillWaitingForUpdate)
{
successiveTimerActivationCount ++;
// force LM restart if value too big , e.g. 30 ( stop + start )
return;
}
successiveTimerActivationCount = 0 ;
isStillWaitingForUpdate = YES;
/* isRecordingX is always true */
if (isSignificant && isRecordingSig) [self startSignificant ];
if (isGPS && isRecordingGPS) [self startGps];
}
// this is called in delegate method only
-(void) timerStopLocationServices
{
isStillWaitingForUpdate = NO;
if (isGPS) [ self stopGps] ;
if (isSignificant) [self stopSignificant];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// verify accuracy and stuff
if ( isStillWaitingForUpdate && _other_validations_ )
{
// store it
[self timerStopLocationServices] ;
}
}
The start and stop methods simply verifiy if the locationmanager is nil, if yes they call createManager and then call start & stopUpdatingLocation.
The creation of the LM looks like this :
-(void)createManager
{
#synchronized (self)
{
if (locationManager != nil) {
[self releaseManager]; // stop timer, stop updating , reelase previous if exists
}
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
double desired;
// accuracy is an init param, snap to one smaller constant
// generally 100-200
if (accuracy >= kCLLocationAccuracyThreeKilometers) desired = kCLLocationAccuracyThreeKilometers; else
if (accuracy >= kCLLocationAccuracyKilometer) desired = kCLLocationAccuracyKilometer; else
if (accuracy >= kCLLocationAccuracyHundredMeters) desired = kCLLocationAccuracyHundredMeters; else
if (accuracy >= kCLLocationAccuracyNearestTenMeters) desired = kCLLocationAccuracyNearestTenMeters; else
if (accuracy >= kCLLocationAccuracyBest) desired = kCLLocationAccuracyBest; else
if (accuracy >= kCLLocationAccuracyBestForNavigation) desired = kCLLocationAccuracyBestForNavigation;
locationManager.desiredAccuracy = desired;
locationManager.distanceFilter = distanceFilter;
}
}
Did anyone experienced something like this? Any ideas are welcome :)
Thanks!

I can at least confirm "blocked location managers", though in a slightly different context:
From my experience, if you create two location managers with different accuracy settings, start updates for both and then only stop updates for the one with the higher accuracy requirement, then the other one no longer receives any updates.
You are apparently only using one manager, but the way your manager gets stuck seems to be the same: In the case described above, updates can also be restarted by using the map application (or any similar).
My workaround is the following: Whenever I stop one manager, I also reset the distance filters of all others (stored in an NSSet called myCLLocationManagers), like the following:
CLLocationManager * lm;
CLLocationDistance tmp;
for (lm in myCLLocationManagers){
tmp=lm.distanceFilter;
lm.distanceFilter=kCLDistanceFilterNone;
lm.distanceFilter=tmp;
}
This seems to work more reliably than my previous woraround (which was to stop and restart the managers).
Note that kCLLocationAccuracyBestForNavigation and kCLLocationAccuracyBest are (currently) negative values, and that in general, you shouldn't rely on the specific values of all those constants - there's no guarantee that kCLLocationAccuracyHundredMeters==100 (although currently true). I only mention this because it appears like you are directly comparing an "accuracy" variable in meters with those constants.

Related

didUpdateToLocation called multiple times

I have an application in which user track his/her route when jogging or cycling, So i need perfect location, so user's routes will be perfect.
But, I have one problem in this,
locManager = [[CLLocationManager alloc] init];
[locManager setDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
[locManager setDelegate:self];
[locManager startUpdatingLocation];
In viewDidLoad. Using this didUpdateToLocation method called multiple times when I just dont move device a little and on map very strange route draw.
I just cant understand why this happen, if I am doing some wrong or missing something.
Thanks.......
I use locationManager.distanceFilter = 500; (or so) // meters
to prevent multiple calls from happening. just remember to call this BEFORE you start updating your location
You can set the distancefilter of the location manager hope this may help you
locationManager=[[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter=10.0;
[locationManager startUpdatingLocation];
When you first start location services, you'll generally see multiple location updates come whether you're moving or not. If you examine the horizontalAccuracy of the locations as they come in, you'll see that while it's "warming" up it will show a series of locations with greater and greater accuracy (i.e. smaller and smaller horizontalAccuracy values) until it reaches quiescence.
You could disregard those initial locations until horizontalAccuracy falls below a certain value. Or, better, during start up, you could disregard the previous location if (a) the distance between a new location and the old location is less than the horizontalAccuracy of the old location and (b) if the horizontalAccuracy of the new location is less than that of the prior location.
For example, let's assume you're maintaining an array of CLLocation objects, as well as a reference to the last drawn path:
#property (nonatomic, strong) NSMutableArray *locations;
#property (nonatomic, weak) id<MKOverlay> pathOverlay;
Furthermore, let's assume your location update routine is just adding to the array of locations and then indicating that the path should be redrawn:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"%s", __FUNCTION__);
CLLocation* location = [locations lastObject];
[self.locations addObject:location];
[self addPathToMapView:self.mapView];
}
Then the addPathToMapView can therefore remove the second from last location if it's less accurate than the last one and if the distance between them is less than the most recent location's accuracy.
- (void)addPathToMapView:(MKMapView *)mapView
{
NSInteger count = [self.locations count];
// let's see if we should remove the penultimate location
if (count > 2)
{
CLLocation *lastLocation = [self.locations lastObject];
CLLocation *previousLocation = self.locations[count - 2];
// if the very last location is more accurate than the previous one
// and if distance between the two of them is less than the accuracy,
// then remove that `previousLocation` (and update our count, appropriately)
if (lastLocation.horizontalAccuracy < previousLocation.horizontalAccuracy &&
[lastLocation distanceFromLocation:previousLocation] < lastLocation.horizontalAccuracy)
{
[self.locations removeObjectAtIndex:(count - 2)];
count--;
}
}
// now let's build our array of coordinates for our MKPolyline
CLLocationCoordinate2D coordinates[count];
NSInteger numberOfCoordinates = 0;
for (CLLocation *location in self.locations)
{
coordinates[numberOfCoordinates++] = location.coordinate;
}
// if there is a path to add to our map, do so
MKPolyline *polyLine = nil;
if (numberOfCoordinates > 1)
{
polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfCoordinates];
[mapView addOverlay:polyLine];
}
// if there was a previous path drawn, remove it
if (self.pathOverlay)
[mapView removeOverlay:self.pathOverlay];
// save the current path
self.pathOverlay = polyLine;
}
Bottom line, just get rid of locations that are less accurate than the next one you have. You could get even more aggressive in the pruning process if you want, but there are tradeoffs there, but hopefully this illustrates the idea.
startUpdatingLocation
Will continuously update a user's location even when the location does not change. You just need to structure your app to handle these continuous updates according to your needs.
Try reading Apple's documentation on this subject. It is confusing at first but try anyway.
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1
I think this is what you need.startMonitoringForRegion:desiredAccuracy
for Example see the following github link.
Try this Bread Crumb sample code provided by Apple..
http://developer.apple.com/library/ios/#samplecode/Breadcrumb/Introduction/Intro.html
Add this,
[locManager stopUpdatingLocation];
into your updateUserLocation delegate method.
Review the following code snippet:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[_locationManager stopUpdatingLocation];
}
locationManager.startUpdatingLocation() fetch location continuously and didUpdateLocations method calls several times,
Just set the value for locationManager.distanceFilter value before calling locationManager.startUpdatingLocation().
As I set 200 working fine
locationManager.distanceFilter = 200
locationManager.startUpdatingLocation()

Function "didUpdateToLocation" being called without changes

I initialize the locationManager this way:
if (!self.locManager)
{
self.locManager = [[CLLocationManager alloc] init];
self.locManager.delegate = self;
[locManager startMonitoringSignificantLocationChanges];
}
my device is not moving and still "didUpdateToLocation" is being called every time.
What could be a problem?
Thanks
didUpdateToLocation may update for a number of reasons, a good strategy for handling this is to gradually filter results based on timestamp, then required accuracy.
Apple provide a good example in the LocateMe sample app:
- (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;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
// test the measurement to see if it is more accurate than the previous measurement
if (self.bestEffortAtLocation == nil || self.bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy)
{
// store the location as the "best effort"
self.bestEffortAtLocation = newLocation;
// test the measurement to see if it meets the desired accuracy
//
// IMPORTANT!!! kCLLocationAccuracyBest should not be used for comparison with location coordinate or altitidue
// accuracy because it is a negative value. Instead, compare against some predetermined "real" measure of
// acceptable accuracy, or depend on the timeout to stop updating. This sample depends on the timeout.
//
if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
// we have a measurement that meets our requirements, so we can stop updating the location
//
// IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
//
[self stopUpdatingLocation:NSLocalizedString(#"Acquired Location", #"Acquired Location")];
}
}
}
Do you check for location differences? CoreLocation also calls callbacks when other attributes such as accuracy, heading or speed change
startMonitoringSignificantLocationChangesshould give you an initial fix and after that you will get callbacks for "significant changes" (cell tower change etc.)

Core Location First Point Invalid

My first location using Core Location is almost always invalid.
My code is as follows:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
//for saving the data ACCURATELY for calculations
// make sure the coordinates are valid
if ([self isValidLocation:newLocation withOldLocation:oldLocation])
{
mDistance = [newLocation distanceFromLocation:oldLocation];
[[NSNotificationCenter defaultCenter]postNotificationName:#"locationUpdated" object:nil];
}
}
As you can see it checks to see if it is a valid location with isValidLocation. That code is here:
- (BOOL)isValidLocation:(CLLocation *)newLocation
withOldLocation:(CLLocation *)oldLocation
{
// Throw away first point
if (isFirstPoint)
{
NSLog(#"First point thrown away.");
isFirstPoint = NO; //subsequent updates will NOT be the first point
return NO;
}
// Filter out nil locations
if (!newLocation){
NSLog(#"New location invalid");
return NO;
}
if (!oldLocation)
{
NSLog(#"Old location invalid");
return NO;
}
// Filter out points by invalid accuracy
if (newLocation.horizontalAccuracy < 0)
{
return NO;
}
// Filter out points that are out of order
NSTimeInterval secondsSinceLastPoint = [newLocation.timestamp
timeIntervalSinceDate:oldLocation.timestamp];
if (secondsSinceLastPoint < 0){
return NO;
}
// Filter out points created before the manager was initialized
NSTimeInterval secondsSinceManagerStarted = [newLocation.timestamp
timeIntervalSinceDate:locationManagerStartDate];
if (secondsSinceManagerStarted < 0){
return NO;
}
// If the distance is negative
if ([newLocation distanceFromLocation:oldLocation] < 0)
{
return NO;
}
if(newLocation.speed < 0)
{
return NO;
}
// GIANT ELSE: The newLocation is good to use
return YES;
}
Even after checking all of that, my first point is always invalid. For example, I went from work to home, and turned on my location manager at home, yet my first coordinate was from my office at work. How can I fix this?
Here is what happens when I get an invalid first point:
It really depends on your use case. Core Location often returns the device's last known position in order to give you a result as quickly as possible. This location is passed to you before the device has finished acquiring a new location. The last known position can be several kilometers off your current position.
Depending on the type of your app, this might be a totally negligible difference (e.g. if an app just wants to locate the country a user is in) or it might represent an inacceptable error. Core Location can't tell.
It's important for you to decide how to deal with this behavior. Always throwing the first reported location away might not be the best strategy. You might want to store the time when you call startUpdatingLocation and only throw the first reported location away if the system passes it to you within a very brief period of time (say, 1/10th of a second) that makes it likely to be a cached location. Also, the location's timestamp property might be helpful in judging how (in)accurate the reported location can be.
Your test is wrong. The documentation of locationManager:didUpdateToLocation:fromLocation: clearly states that for the first update, the oldLocation is nil. But you don't test for that: you only look at newLocation and then access oldLocation. This can lead to bad values or crashes.

Getting an accurate location with CLLocationManager

I'm beginning to mess around with the CLLocationManager and I am trying to use the callback method below. I went outside to test it on my iPhone, and with the first few updates, I seem to be getting gibberish values, like all of a sudden my distance is 39meters even though I haven't moved anywhere. Or sometimes it will start at 5, and then jump to 20 meters, again without me moving anywhere. I went outside and walked, and the updates from the initial starting point seemed 'ok,' and then when I walked back, I got back to the original 39 meters starting point. I was wondering if what I am doing below is correct. I also included my viewDidLoad method where I initialize my CLLocationManager object.
Is there a way to ensure that my first values are accurate? Thanks in advance.
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (startingPoint == nil) {
NSLog(#"NIL starting point");
self.startingPoint = newLocation;
}
CLLocationDistance distance = [newLocation distanceFromLocation:startingPoint];
NSString *distanceString = [[NSString alloc] initWithFormat:#"%g m", distance];
distanceLabel.text = distanceString;
[distanceString release];
numberOfUpdates++;
NSString *countString = [[NSString alloc] initWithFormat:#"%d", numberOfUpdates];
countLabel.text = countString;
[countString release];
}
GPS is an imperfect technology. Atmospheric conditions, sattelite availability (and position), sky visibility, signals bouncing off nearby objects (buildings) all contribute to it's inherent inaccuracy. Though there is even an "accuracy" value (which is usually pretty good) - even this is not completely reliable.
Airplanes are not allowed to use GPS for precision approaches - even their receivers aren't accurate enough, and they require other technologies (which have their own issues).
Try running the standard "Maps" application and use it as a comparison. I think your code is good - it's jut GPS.
Of course I am saying this because I am working on my own maritime navigation application, an running into all these issues myself.
Though this is an old question I still like to answer. The first call to "didUpdateToLocation" usually is some old value and you should always check the timestamp. From the Apple documentation:
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
// use the value
}
In your didUpdate method, you can test newLocation's .horizontalAccuracy property for an acceptable value and toss any values that are impossible (or even unlikely!).

iPhone Gps logging inaccurate

I'm logging gps points during a walk. Below it shows the function that the coordinates are saved each 5 seconds.
i Did several tests but i cannot get the right accuracy i want. (When testing the sky is clear also tests in google maps shows me that the gps signal is good).
here is the code:
-(void)viewDidAppear:(BOOL)animated{
if (self.locationManager == nil){
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
// only notify under 100 m accuracy
locationManager.distanceFilter = 100.0f;
locationManager.desiredAccuracy= kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
}
- start logging
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(getData) userInfo:nil repeats:YES];
</code>
<code>
-(void)getData{
int distance;
// re-use location.
if ([ [NSString stringWithFormat:#"%1.2f",previousLat] isEqualToString:#"0.00"]){
// if previous location is not available, do nothing
distance = 0;
}else{
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:previousLat longitude:previousLong];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:latGlobal longitude:longGlobal];
distance = [loc1 getDistanceFrom: loc2];
}
// overwrite latGlobal with new variable
previousLat = latGlobal;
previousLong = longGlobal;
// store location and save data to database
// this part goes ok
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// track the time to get a new gps result (for gps indicator orb)
lastPointTimestamp = [newLocation.timestamp copy];
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
// test the age of the location measurement to determine if the measurement is cached
// don't rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
latGlobal = fabs(newLocation.coordinate.latitude);
longGlobal= fabs(newLocation.coordinate.longitude);
}
I have taken a screenshot of the plot results (the walk takes 30 minutes) and an example of what i'am trying to acomplish:
http://www.flickr.com/photos/21258341#N07/4623969014/
i really hope someone can put me in the right direction.
Looking at your plots - This is exactly what I see too in an app I am working on.
Looking at your code. Whenever location is updated, locationManager calls didUpdateToLocationFromLocation - polling at 5s intervals will give you a lot of points at the same location. (but not relevant to the question)
Also I think you are leaking a lastPointTimestamp (not relevant to the question)
Right - the jumping around - you can look at the accuracy of the points : you do this in locationManager anyway but only check for <0. Is there a pattern of what the horizontal accuracy is on the jumping points ? The accuracy figure may be much worse then for other points, or one specific value (caused by a switch to cell tower triangulation).
Finally, you may need to implement filtering. Kalman filters are the over-the-top way to go, but I am looking at using low-pass filters combined with some basic physics (max acceleration & speed for walking, cycling, running, driving etc) to improve results.
Happy to collaborate on this.