Deferring Location Updates in Background - ios7

I have a app which collects location data in foreground and background. To save battery i want to use the allowDeferredLocationUpdatesUntilTraveled property as explained in Apple Doc
From the documents, allowDeferredLocationUpdatesUntilTraveled gets set(based on time and distance) in foreground. Once app goes in the background we won't receive regular location updates instead we receive them based on the allowDeferredLocationUpdatesUntilTraveled.
I have implemented following code but the deferring does not get called in the background.
#pragma mark - Location Manager
-(void) setLocationManager
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"didUpdateLocations");
if (!deferringUpdates)
{
CLLocationDistance distance = 200;
NSTimeInterval time = 60;
[locationManager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time];
deferringUpdates = YES;
}
}
-(void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error
{
NSLog(#"didFinishDeferredUpdatesWithError");
}
SetLocationManager gets called in the foreground and works fine. Once app goes in the background i still receive regular location updates rather than allowDeferredLocationUpdatesUntilTraveled.
I have also set the following values in the info.plist file
Background Fetch
Background Location Updates
Device Capabilities - location service
Anyone luck with implementing this?

You need to set deferringUpdates back to NO within didFinishDeferredUpdatesWithError : as per Apple documentation, the "delegate’s locationManager:didFinishDeferredUpdatesWithError: method is called exactly once for each time you call (allowDeferredLocationUpdatesUntilTraveled)".
Thus allowDeferredLocationUpdatesUntilTraveled is only called once until deferringUpdates is NO.

Related

Latitude and Longitude 0 when called second time in Objective-C

I am using the below code to get coordinates on click of a button
-(CLLocationCoordinate2D) getLocation{
CLLocationCoordinate2D coordinate;
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled]) {
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
coordinate = [location coordinate];
}
else {
coordinate.latitude = 0.0;
coordinate.longitude = 0.0;
}
return coordinate;
}
When the button is clicked for the first time, I do get my valid coordinates, but if I click the button again, The latitude and longitude values are 0.0000
Any suggestions
Please initialize the CLLocationManager outside the method.Take the You can initialize in viewdidload method.
It may helps to you
You cannot expect [locationManager location] to return anything useful immediately after activating a location manager with [locationManager startUpdatingLocation] .
CLLocationManager takes time to acquire a location. You need to set the CLLocationManager's delegate (eg, to 'self') and then use the delegate method - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations; to get notified when the location manager has got a location that you can use.
See: https://developer.apple.com/reference/corelocation/cllocationmanagerdelegate/1423615-locationmanager?language=objc
(If you only want one location, and not a continuous stream of location updates, instead of calling 'startUpdatingLocation' call [locationManager requestLocation] - but even then you still need to use the delegate method to be notified when a location has been acquired).
You need to split out the code for creating and starting the location manager to where it is only run once (only need one location manager for the app) - eg, viewDidLoad. Then the rest of the code, to process the locations acquired, should go in the delegate method.
In reality, if you want you button click to have a location immediately, you need to have your location manager running and updating locations before your button is available to be clicked. Eg, make your button enabled=NO and when you start getting locations via the delegate method, set the button enabled=YES.

didUpdateLocations does not get called when app enters foreground, core location, ios

my goal is whenever app enters fore ground, i will fetch the location to update my weather forecast. What I do is
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
}
- (void)viewWillAppear:(BOOL)animated
{
self.locationManager.delegate = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}
#pragma mark - Click to get weather
-(void)enterForeground {
[self.locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog#"didUpdateLocations";
}
However, enterForeGround does get call whenver I enter fore ground but didUpdateLocations doesnot get called all the time.
I dont know what I am missing some crucial things for location service. Please advice me if you have any ideas.
Thanks
There is never a guarantee that didUpdateLocations will be called. The thing you can do is when viewDidLoad is called, you can request que last location with. self.locationManager.location.
You can now check the timestamp and the precision of that location. If the data is too old or innacurate for your needs, you then call startUpdatingLocation, and when you get a fix according to your filter and accuracy, didUpdateLocations will be called.
First you need to add Location Services in background by going to Targets -> Capabilities and under "Background Modes" check on "Location Updates".
Secondly you need to start location update [self.locationManager startUpdatingLocation] somewhere appropriately (for you code provided above in viewWillAppear seems to be the best choice)
- (void)viewWillAppear:(BOOL)animated
{
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation]
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}
Now when you app enter background mode and reenter Foreground, the locationManager delegate method should be called.

iOS7 Core Location not updating

I have a very simple app example that initialises and updates the users location.. On device it successfully throws another callback location every second or so however on device (iPhone running iOS7) is calls the method once and then mysteriously stops...
//Setup Location Manager in ViewDidLoad
locationManager = [[CLLocationManager alloc] init];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"location services not turned on");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(#"loactions %#", locations);
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"new location %f, and old %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
In iOS6 this app worked perfectly and continuously updated the devices location... What has changed since iOS7?
There are a few things here:
1- I don't see anywhere the property: pausesLocationUpdatesAutomatically. The default for this property is Yes. This means that depending on your activityType (see #2) below, the GPS will pause updates and this could be the reason you are not getting updates. The algorithm is a black box that only Apple knows and maybe it somehow changed between iOS6 and iOS7. Setting pausesLocationUpdatesAutomatically to NO can impact the battery.
2- You should set your activityType depending on your application. The default is CLActivityTypeOther which I am not sure how it impact the GPS algorithm and #1 above. So in order to test your app initially, I would set the activityType appropriately and change pausesLocationUpdatesAutomatically to No. In my test, I would get an update about every second consistently (I tested it overnight).
3- Location updates testing requires movement. In order to get better results, I would use the activityType you set, for testing. In other words, if activityType is CLActivityTypeFitness, I would walk around to test it, etc..
4- locationManager didUpdateToLocation fromLocation is deprecated in iOS7. In addition if locationManager didUpdateLocations is implemented, the former will not be called. So in your case above, locationManager didUpdateToLocation fromLocation is not being called.
5- There is no real battery usage difference between kCLLocationAccuracyBestForNavigation and kCLLocationAccuracyBest. On the other hand, kCLLocationAccuracyBestForNavigation uses top speed GPS and in addition combines it with accelerometer data.
So I would start with setting activityType, setting pausesLocationUpdatesAutomatically to NO and changing desiredAccuracy to kCLLocationAccuracyBestForNavigation. Once you are getting continuous updates, then I would set pausesLocationUpdatesAutomatically to Yes and try to work the code to achieve the same app usability.
Hope this helps

CLLocationManager updates only on Simulator Not on Devices

Here we have to update the current location by using the location manager,and its correctly updating on simulator but its not updating on device only 4 or 5 times only repeated.why the location is not updated frequently kindly hep me to solve this problem
Here i used code is showed below
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[locationManager startUpdatingLocation];
Delegate Method:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"newLocation: %#",newLocation);
}
This is the delegate method is calling four or five times.
If you are using location accuracy as 'kCLLocationAccuracyBestForNavigation', your device should remain plugged in.
Better you set it as 'kCLLocationAccuracyBest'. Also move to significant distance to hit the delegate. initially it will hit 4-5 times to locate you. Once your location is identified, it will call the delegate when there will be change in your location.
So, in delegate write something in file stored in documents directory in append mode. log the lat/long and Time details into it. Now move for some distance.
Join the mobile and get the file from documents directory. It must have logg the required details.
Here i solved this problem using this delegate method
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
}

ios CLLocationManager won't get location second time

I have a getLocation method that initializes my CLLocationManager and calls startUpdatingLocation. After I get the user's location, I call stopUpdatingLocation.
Later, when the user presses refresh, I call a method reloadData which calls getLocation so I can get the user's latest location. However, this never calls the locationManager:didUpdateToLocation:fromLocation
method.. so I never get the user's latest location. What could be the issue?
-(void) getLocation {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
- (void) locationManager: (CLLocationManager *)manager
didUpdateToLocation: (CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (oldLocation!= nil) { // make sure to wait until second latlong value
[self setLatitude:newLocation.coordinate.latitude];
[self setLongitude: newLocation.coordinate.longitude];
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
self.locationManager = nil;
[self makeUseOfLocationWithLat:[self getLatitude] andLon:[self getLongitude]];
}
}
-(void) reloadData {
[self getLocation];
}
Is it really necessary to allocate a new CLLocationManager? Try just allocate it once (in your init for example) and just call startUpdatingLocation and stopUpdatingLocation on demand.
For me, this solution works great.
Do you move during testing this? Because I think the callback will only be triggered, when:
you call startUpdatingLocation
your location changes
the location manager gets better results (more detailed)
So I think for your use-case: as you don't move, the callback locationManager:didUpdateToLocation:fromLocation: will only be called once after you hit refresh and as there is no old location, you will not go into the if case.
Another thing: you should definitely have only one CLLocationManager in your class. I only use one per project/application (wrapped in a singleton). This is the preferred way to do! Also I think this will retain the oldLocation value so that your problem may be resolved by changing this.
Best,
Christian
you can try this ,this will help u to update for every time when open the page.Cause if u put startUpdatingLocation in viewdidload ,it will get load only for the first time
-(void)viewWillAppear:(BOOL)animated
{
[locationManager startUpdatingLocation];
}