CLLocationManager updateLocation never called while app is in background - background

I've read so many question here at stackoverflow and I am still having issues with CLLocationManager.I have already added keys in info.plist (NSLocationAlwaysAndWhenInUseUsageDescription,NSLocationWhenInUseUsageDescription,NSLocationAlwaysAndWhenInUseUsageDescription). My app supports ios 9.0 to 11.x.
Update:- I'm testing on iphone6 ios 11.0.3 physical device
My Approach -
1. Start updating location after while using the app permission.
2. When app goes into background stop location manager to remove Blue Banner (Banner Of Shame)
3.Fire a periodic timer of 30 seconds and start location manager again.
This time I never got the delegate callback didUpdateLocation
I have a singleton class called LocationManager.
Here is my code from LocationManager and AppDelegate
LocationManager
- (void)startLocatingUser {
//Locate User
_locationMeasurements = [NSMutableArray array];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.pausesLocationUpdatesAutomatically = NO;
self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;
if ([self.locationManager respondsToSelector:#selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
if(IS_OS_8_OR_LATER) {
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
}
if (#available(iOS 11.0, *)) {
self.locationManager.showsBackgroundLocationIndicator = NO;
}
[self.locationManager startUpdatingLocation];
}
- (void)stopLocatingUser {
if(self.locationManager) {
[self.locationManager stopUpdatingLocation];
}
}
AppDelegateCode
- (void)applicationWillResignActive:(UIApplication *)application {
_isBackgroundMode = YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
LocationManager* locationManager = [LocationManager sharedLocationManager];
[locationManager stopLocatingUser];
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
self.bgTimer = [NSTimer scheduledTimerWithTimeInterval:30.0
target:self
selector:#selector(startTrackingBg)
userInfo:nil
repeats:YES];
}
-(void)startTrackingBg {
dispatch_async(dispatch_get_main_queue(), ^{
LocationManager* locationManager = [LocationManager sharedLocationManager];
[locationManager startLocatingUser];
});
NSLog(#"App is running in background");
}
I am never getting this delegate callback in background once I stop and start location manager again.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
What I simply want is whenever user puts the app in background. I want to hide the banner of shame and then I need periodic location updates in background and send them to server.

Related

iOS 8 Error when requesting Authorization

I am having much trouble trying with requesting the location services authorization. I know there are other posts on this forum, but I did not solve my problem with their solution.
This is the error popping up in xCode:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
I have added both the required keys for the Plist.
Another important point is that when I start it in the simulator, I can go into the setting manually and enable location services and then the App does work. However, when I restart the App it does not work and I get the same message above.
I want to prompt the user with the option to enable location services.
Unfortunately, this code does not prompt the authorization for location services.
Please help I have been pulling my hair out for hours.
1
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
//Initialize the map and specifiy bounds
self.myMapView =[[MKMapView alloc]initWithFrame:self.view.bounds];
//specifcy resizing
self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//show the User's location and set tracking mode
self.myMapView.showsUserLocation = YES;
self.myMapView.userTrackingMode = MKUserTrackingModeFollow;
//add the VIEW!!
[self.view addSubview:self.myMapView];
}
And here is the Function I want to call
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
This is the delegate method about location service
You can get your AuthorizationStatus from status.Such as kCLAuthorizationStatusDenied
You simply call
[self.locationManager requestAlwaysAuthorization];in viewdid load,and monitor AuthorizationStatus in delegate method above,if user deny your location service,show a alertview

Display background notification when CLProximityNear

I am trying to display a notification when my app is in the background and the device enters a region of an iBeacon and when their CLProximity is Near the notification is working, but it keeps appearing at 1 second intervals:
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#"Entered beacon region");
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
- (void) locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region{
NSLog(#"Left region");
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
}
- (void) locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
- (void) locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
CLBeacon *beacon = [[CLBeacon alloc] init];
beacon = [beacons lastObject];
self.uuidLabel.text = beacon.proximityUUID.UUIDString;
if(beacon.proximity == CLProximityUnknown) {
distanceLabel.text = #"Unknown Proximity";
[self.view setBackgroundColor:[UIColor grayColor]];
} else if (beacon.proximity == CLProximityImmediate) {
distanceLabel.text = #"Immediate";
[self.view setBackgroundColor:[UIColor redColor]];
} else if (beacon.proximity == CLProximityNear) {
distanceLabel.text = #"Near";
[self.view setBackgroundColor:[UIColor orangeColor]];
UILocalNotification *inRange = [[UILocalNotification alloc] init];
inRange.alertBody = [NSString stringWithFormat:#"Entered region!"];
inRange.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:inRange];
} else if (beacon.proximity == CLProximityFar) {
distanceLabel.text = #"Far";
[self.view setBackgroundColor:[UIColor blueColor]];
}
}
Should there be a method call after the notification is displayed to tell the app that it has been displayed and not to keep calling the didRangeBeacons method until the user goes out of range and back in again?
When ranging beacons, locationManager:didRangeBeacons:inRegion will be called every second, as you've identified. Each time, the beacons parameter will contain an array of all visible beacons.
It's up to your app to contain logic to determine whether a new beacon is visible, or whether you've already notified the user about it. I suggest you store an array of previously discovered beacons, and each time locationManager:didRangeBeacons:inRegion is called you compare your list with the contents of the beacons parameter. You then should be able to tell whether any new beacons have been found.
The multiple notifications can be solved like this:
If you only want the notification to be sent once, simply define an alreadyDisplayed flag, which gets set after the notification is sent, then check its value before sending.
Like this:
BOOL alreadyDisplayed = NO;
...
- (void) locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
...
else if (beacon.proximity == CLProximityNear) {
distanceLabel.text = #"Near";
if (!alreadyDisplayed) {
[self.view setBackgroundColor:[UIColor orangeColor]];
alreadyDisplayed = YES;
UILocalNotification *inRange = [[UILocalNotification alloc] init];
inRange.alertBody = [NSString stringWithFormat:#"Entered region!"];
inRange.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:inRange];
}
}
...
}
But you still have a second problem:
If you want to do this in the background as your question title suggests, this isn't going to work at all. The problem is that after iOS detects that your phone entered an iBeacon region in the background, it only lets it run for five seconds before putting it to sleep. Because the range of an iBeacon is about 50 meters, the most likely case is that this five second interval will start when you are at the edge of that 50 meter range. It is very unlikely that the user will walk so fast that they enter the "Near" proximity within the 5 seconds you have before your app is put to sleep. For this reason, it is generally not possible to take specific action based upon an specific proximity when you are in the background.
That said, if you want to do this in the foreground, this will work just fine if you make changes to keep the notifications from coming every second.

Can we show user location in offline in MKMapview

Can we get current user location "That blue ball which is animating" when our device is offline.when i tried to get current user location and log it i'm getting 0.00000 for both longitude and latitude here is the code that i used to get current user location.I'm using ipad mini to test it.I have also added CLLocationManagerDelegate in .h file.
- (void)viewDidLoad {
[self getUserLocation];
self.myMapView.showsUserLocation = YES;
}
-(void)getUserLocation{
if ([CLLocationManager locationServicesEnabled]) {
locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[locationManager startUpdatingLocation];
}else{
NSLog(#"User location Disabled");
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentGPSLocation = newLocation;
if (currentGPSLocation != nil) {
currentLocation.latitude = self.myMapView.userLocation.coordinate.latitude;
currentLocation.longitude = self.myMapView.userLocation.coordinate.longitude;
currentLocationWalk.latitude=self.myMapView.userLocation.coordinate.latitude;
currentLocationWalk.longitude=self.myMapView.userLocation.coordinate.longitude;
NSLog(#"didUpdateToLocation: %f,%f", self.myMapView.userLocation.coordinate.latitude,self.myMapView.userLocation.coordinate.longitude);
statusLabel.textColor = [UIColor blackColor];
statusLabel.text = [NSString stringWithFormat:#"%f",self.myMapView.userLocation.coordinate.latitude];
statusLabel1.text = [NSString stringWithFormat:#"%f",self.myMapView.userLocation.coordinate.longitude];
}
}
You are not using ARC (I strongly suggest using it, it avoid most of the memory management errors!).
Therefore it might be that "locationManager" is a instance variable that is not retained (maybe you did not declare it as a retained property).
In this case, it might have been released already when your code returns to the main run loop, where the autorelease pool is drained.
This line
locationManager = [[[CLLocationManager alloc] init] autorelease];
is not a good idea.
define the locationManager as a property,
init the locationManager in viewDidLoad(), but remove the autorelease!
and relase the locationManager only when the viewController is unloaded (there where you release the other properties)

iOS App Background Location (Push Notifications)

I face an issue where my app requires the users location when they receive a push notification while the app is running in the background.
After doing a bit of reading I'm under the impression that this isn't possible, i.e:
1) App in background
2) Push notification received
3) Get users location and execute block of code.
I found this post on here that suggests you can run a task every N amount of minutes to get the users location. So using this I could check say every ten minutes which would work but it would be a waste of the users battery if I kept activating the GPS. Therefore I was wondering can I tell within my background task if the user has any push notification waiting for my app? That way I would check if they did every ten minutes and only activate the GPS if they did.
Perhaps I'm going about this all the wrong way, I would really appreciate any advice. Sorry for not having any of the code for the background task yet as I'm still trying to get it to work.
[UPDATE]
Thanks Dustin for your advice. After a bit of testing I've decided to go with an easier option. I am now using the Apple Significant Location Changes. I store the changes in an array, I've set this to only update if the last change was greater than 10min ago. Then when the app becomes active I match the closest time in the array to the time the push notification was sent and use that location.
As discussed I used alternative solution, here it is:
Under viewDidLoad or didFinishingLaunchingWithOptions add:
locationsLogged = [[NSMutableArray alloc] init];
lastLocationTime = [[NSDate alloc] init]
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
Under applicationDidEnterBackground add:
[locationManager startMonitoringSignificantLocationChanges];
Add:
-(void) storeLocations:(CLLocation *)location
{
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
[locationsLogged addObject:location];
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
NSDate *now = [NSDate date];
NSTimeInterval diff = [now timeIntervalSinceDate:lastLocationTime];
if ((int)diff > 600) {
if (isInBackground)
{
[lastLocationTime release];
lastLocationTime = [[NSDate alloc] init];
[self storeLocations:newLocation];
}
else
{
// ...
}
}
}
Then on applicationDidBecomeActive you can use whatever logic you need to apply location information.

handling location event with didFinishLaunchingWithOptions in background mode or after app was terminated

I call startMonitoringSignificantLocationChanges in location manager init.
I expect that if there is a location event didFinishLaunchingWithOptions will be launched and execute the following code. (including background mode and if app was terminated)
The app freezes (black screen when i try to launch it after a few hours in the background in different location)
Probably i'm doing something wrong when i get a location event. I would appreciate if someone has an idea what's the problem.
By the way, there is no way to simulate this kind of location event but physically move to a different location with different cell tower. is there? ... :(
LocationController.m :
- (id)init
{
self = [super init];
if (self != nil) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[self.locationManager startUpdatingLocation];
[self.locationManager startMonitoringSignificantLocationChanges];
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(stop) userInfo:nil repeats:NO];
}
return self;
}
appdelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
id locationValue = [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey];
if (locationValue)
{
[[LocationController sharedInstance] startMonitoringSignificantLocationChanges];
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
[self updateLocationService];
return YES;
}
}
- (void) updateLocationService {
[[LocationController sharedInstance] start];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(stop) userInfo:nil repeats:NO];
}
- (void) stop {
[[LocationController sharedInstance] stop];
}
Thank you!
Your didFinishLaunchingWithOptions: method does not return anything if there is no UIApplicationLaunchOptionsLocationKey set.
Just move the return statement outside your if clause:
if (locationValue)
{
...
}
return YES;