ios 9 app not reporting location in background - ios

I am writing (in Swift) an iOS 9 app that needs location updates including in background mode. The problem is that I only get location updates in foreground. I think I have done everything correctly:
In info.plist:
Specified a value for NSLocationAlwaysUsageDescription.
Specified a value for NSLocationUsageDescription.
Specified a value for NSLocationWhenInUseUsageDescription.
Included "location" in UIBackgroundModes.
Included "gps" and "location-services" in UIRequiredDeviceCapabilities
Started the location manager as follows:
let locationManager = CLLocationManager()
locationManager.desiredAccuracy =
kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 250.0
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
I have also verified that
locationManager.pausesLocationUpdatesAutomatically is false.
I get no location updates while the app is not in the foreground. The only time I do get location updates is if I bring the app to foreground, and even then, not all the time.
Any idea what's going wrong? Or my expectations incorrect?

How are you sending the app to the background? If you swipe to kill then your app won't automatically restart to receive the location events. I don't see it in your code, did you call requestAlwaysAuthorization? You might also want to implement LocationManager:didFailWithError just to see if that gives you any ideas.

Related

How to get Location coordinates when app in background mode at the same time suspend mode

I used loc_manager.startMonitoringSignificantLocationChanges() but didUpdateLocations not calling in foreground ,background and suspend mode can anyone help me please,
override func viewDidLoad() {
super.viewDidLoad()
loc_manager.requestAlwaysAuthorization()
loc_manager.allowsBackgroundLocationUpdates = true
loc_manager.delegate = self
loc_manager.desiredAccuracy = kCLLocationAccuracyBest
loc_manager.pausesLocationUpdatesAutomatically = false
loc_manager.distanceFilter = kCLDistanceFilterNone
}
For Location in foreground
In the foreground the CLLocationManager object and delegates will do fine. This will also work with the 'while in use' location permission.
For Location in background
Please enable the Background Modes from the capabilities of the project and enable the 'Location updates'. After enabling this, the only configuration to get the updates in the background(not in killed state) is to set'allowsBackgroundLocationUpdates' to true(which you have done already).
For more information on getting location in the background follow :
https://developer.apple.com/documentation/corelocation/cllocationmanager/1620568-allowsbackgroundlocationupdates
For location in application suspended or killed
Here the significant location changes are only needed when you want to get the location when the application is killed by the user(or Suspended). This significant location change will launch the application in background and read the location of the device. This mode needs 'Always authorised' location permission.
For significant location changes while the application is in killed state, follow below link. This is in objective C but it can be easily done in swift also.
http://mobileoop.com/getting-location-updates-for-ios-7-and-8-when-the-app-is-killedterminatedsuspended
Hope this helps.

How can I update user location continuously? [duplicate]

I've created a simple app which tracks user location and creates local notification for every time location is updated.
I enabled the background modes below,
let locationManager = CLLocationManager()
open override func viewDidLoad() {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 10
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let notification = UILocalNotification()
notification.alertBody = "location updated"
notification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(notification)
}
I set string for NSLocationAlwaysUsageDescription and ask for permission. User grant permission for always usage when the app loaded first time.
It's working well when app is in the foreground, when it goes background still working at least in 5-40 minutes time range which is changeable
by battery or other opened apps.
The problem is why it stops working, Isn't it expected to be keep working?
I've never seen a time limit in Apple docs.
Switch to significant location updates when the app moves to background. iOS will unload the app if it keep alive in the background indefinitely.
locationManager.pausesLocationUpdatesAutomatically = false
Reduce Accuracy
Set the desiredAccuracy property of the location manager object
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
You can use one of the CLLocationAccuracy constants
IMPORTANT
By default, standard location updates on iOS devices run with an accuracy level of best. Change these settings to match
your app’s requirements. Otherwise, your app will unnecessarily waste
energy.
Auto-Pause
Set the pausesLocationUpdatesAutomatically property of the location manager object to true
self.locationManager.pausesLocationUpdatesAutomatically = true
IMPORTANT
For apps that have in-use authorization, a pause to location updates
ends access to location changes until the app is launched again and
able to restart those updates. If you do not wish location updates to
stop entirely, consider disabling this property and changing location
accuracy to kCLLocationAccuracyThreeKilometers when your app moves
to the background. Doing so allows you to continue receiving location
updates in a power-friendly manner.
Allow background updates
Set the allowsBackgroundLocationUpdates property of the location manager object to true
self.locationManager.allowsBackgroundLocationUpdates = true
Apps that want to receive location updates when suspended must include
the UIBackgroundModes key (with the location value) in their app’s
Info.plist file and set the value of this property to true. The
presence of the UIBackgroundModes key with the location value is
required for background updates
Specify an Activity Type
Set the activityType property to let Core Location know what type of location activity your app is performing at a given time
self.locationManager.activityType = .automotiveNavigation
You can use one of the CLActivityType cases
Defer Location Update
On supported devices with GPS hardware, you can let the location
manager defer the delivery of location updates when your app is in the
background. For example, a fitness app that tracks the user’s location
on a hiking trail can defer updates until the user has moved a certain
distance or a certain period of time has elapsed.
Energy Efficiency Guide for iOS Apps - Location Best Practices
GettingLocationWhenSuspended
After searching for references (talking about any limitation), I assume that Apple Core Location Best Practices video session could be useful! at 06:53 talking about standard location in the background:
furthermore, Core Location won't take any action to ensure your app
continues to run, so if you have background run for some reason and
you decide to start a location session you might get some updates, but
you might also get suspended before you receive all information that
you hope to receive...
Actually, I faced this issue before, -as a workaround- the core location was used to keep tracking the location of the user to do unrelated functionality to its location -which is uploading files-, but this workaround didn't work since iOS 9 has been released; I even posted a question referring to this issue.
However, it seems your case is not identical to what I faced, if you are aiming to:
... creates local notification for every time location is updated.
then you might need to follow the approach of integrating with User Notification Framework - UNLocationNotificationTrigger:
The geographic location that the user must reach to enable the
delivery of a local notification.
It is also mentioned in the video session (08:59).
Probably, this is could be not what are you looking for, but since we have no guarantee that the background execution will continue running, you might -somehow- find a way to integrate it in your app to achieve the desired functionality.
Update for iOS 11:
You might need to check this answer for the proper way to request the location access.
By the sound of it the app is being killed due to memory constraints.
It should however be re-launched when a new location becomes available, as described here: https://developer.apple.com/documentation/uikit/uiapplicationlaunchoptionskey/1623101-location
You should see application(_:didFinishLaunchingWithOptions:) being called, and the 'location' key should be present in the launch options. You'll can then re-create whatever is consuming the locations and continue recording.
If it's not being re-launched it could be too memory hungry. Check the memory consumption of the app and see if applicationDidReceiveMemoryWarning(_:) is being called.
I assume you haven't implement background task. You can read here.
In the above link under section "Implementing Long-Running Tasks" point no. 3 is your situation, so it's valid you can use background location update in your project and for same you need to implement a background task too.
There are three way to track user location(as per above link under section "Tracking the User’s Location" ) :-
Foreground-only location services (which works in your case)
The significant-change location service (Recommended), but I think it is not usable in your case as you want to update user location per 10 meter and it works for ~500 meters, for more please see here
Background location services (I think you are trying for this) and solution is to add a background task.
Below is example of background task and you can modify as per your requirement, it works for me since last 2 hours and my app still update location in background.
.
In your AppDelegate class please update below function and then run your app in background.
func applicationDidEnterBackground(_ application: UIApplication) {
application.beginBackgroundTask(withName: "") {}
}
And below is my ViewController class
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self;
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.allowsBackgroundLocationUpdates = true
locationManager.distanceFilter = kCLDistanceFilterNone
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didUpdateLocations \(Date())")
self.locationManager.stopUpdatingLocation()
}
}
I ran into this where a QT app would stop getting location events in the background after an hour or two.
In the App Delegate when the app would go into the background I would stop the CLLocationManager, decrease the Accuracy from kCLLocationAccuracyBest to kCLLocationAccuracyNearestTenMeters AND increase the distance filter from None to 50 meters and it would then track for 24+ hours.

Location tracking stops after a while when app is in the background

I've created a simple app which tracks user location and creates local notification for every time location is updated.
I enabled the background modes below,
let locationManager = CLLocationManager()
open override func viewDidLoad() {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 10
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let notification = UILocalNotification()
notification.alertBody = "location updated"
notification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(notification)
}
I set string for NSLocationAlwaysUsageDescription and ask for permission. User grant permission for always usage when the app loaded first time.
It's working well when app is in the foreground, when it goes background still working at least in 5-40 minutes time range which is changeable
by battery or other opened apps.
The problem is why it stops working, Isn't it expected to be keep working?
I've never seen a time limit in Apple docs.
Switch to significant location updates when the app moves to background. iOS will unload the app if it keep alive in the background indefinitely.
locationManager.pausesLocationUpdatesAutomatically = false
Reduce Accuracy
Set the desiredAccuracy property of the location manager object
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
You can use one of the CLLocationAccuracy constants
IMPORTANT
By default, standard location updates on iOS devices run with an accuracy level of best. Change these settings to match
your app’s requirements. Otherwise, your app will unnecessarily waste
energy.
Auto-Pause
Set the pausesLocationUpdatesAutomatically property of the location manager object to true
self.locationManager.pausesLocationUpdatesAutomatically = true
IMPORTANT
For apps that have in-use authorization, a pause to location updates
ends access to location changes until the app is launched again and
able to restart those updates. If you do not wish location updates to
stop entirely, consider disabling this property and changing location
accuracy to kCLLocationAccuracyThreeKilometers when your app moves
to the background. Doing so allows you to continue receiving location
updates in a power-friendly manner.
Allow background updates
Set the allowsBackgroundLocationUpdates property of the location manager object to true
self.locationManager.allowsBackgroundLocationUpdates = true
Apps that want to receive location updates when suspended must include
the UIBackgroundModes key (with the location value) in their app’s
Info.plist file and set the value of this property to true. The
presence of the UIBackgroundModes key with the location value is
required for background updates
Specify an Activity Type
Set the activityType property to let Core Location know what type of location activity your app is performing at a given time
self.locationManager.activityType = .automotiveNavigation
You can use one of the CLActivityType cases
Defer Location Update
On supported devices with GPS hardware, you can let the location
manager defer the delivery of location updates when your app is in the
background. For example, a fitness app that tracks the user’s location
on a hiking trail can defer updates until the user has moved a certain
distance or a certain period of time has elapsed.
Energy Efficiency Guide for iOS Apps - Location Best Practices
GettingLocationWhenSuspended
After searching for references (talking about any limitation), I assume that Apple Core Location Best Practices video session could be useful! at 06:53 talking about standard location in the background:
furthermore, Core Location won't take any action to ensure your app
continues to run, so if you have background run for some reason and
you decide to start a location session you might get some updates, but
you might also get suspended before you receive all information that
you hope to receive...
Actually, I faced this issue before, -as a workaround- the core location was used to keep tracking the location of the user to do unrelated functionality to its location -which is uploading files-, but this workaround didn't work since iOS 9 has been released; I even posted a question referring to this issue.
However, it seems your case is not identical to what I faced, if you are aiming to:
... creates local notification for every time location is updated.
then you might need to follow the approach of integrating with User Notification Framework - UNLocationNotificationTrigger:
The geographic location that the user must reach to enable the
delivery of a local notification.
It is also mentioned in the video session (08:59).
Probably, this is could be not what are you looking for, but since we have no guarantee that the background execution will continue running, you might -somehow- find a way to integrate it in your app to achieve the desired functionality.
Update for iOS 11:
You might need to check this answer for the proper way to request the location access.
By the sound of it the app is being killed due to memory constraints.
It should however be re-launched when a new location becomes available, as described here: https://developer.apple.com/documentation/uikit/uiapplicationlaunchoptionskey/1623101-location
You should see application(_:didFinishLaunchingWithOptions:) being called, and the 'location' key should be present in the launch options. You'll can then re-create whatever is consuming the locations and continue recording.
If it's not being re-launched it could be too memory hungry. Check the memory consumption of the app and see if applicationDidReceiveMemoryWarning(_:) is being called.
I assume you haven't implement background task. You can read here.
In the above link under section "Implementing Long-Running Tasks" point no. 3 is your situation, so it's valid you can use background location update in your project and for same you need to implement a background task too.
There are three way to track user location(as per above link under section "Tracking the User’s Location" ) :-
Foreground-only location services (which works in your case)
The significant-change location service (Recommended), but I think it is not usable in your case as you want to update user location per 10 meter and it works for ~500 meters, for more please see here
Background location services (I think you are trying for this) and solution is to add a background task.
Below is example of background task and you can modify as per your requirement, it works for me since last 2 hours and my app still update location in background.
.
In your AppDelegate class please update below function and then run your app in background.
func applicationDidEnterBackground(_ application: UIApplication) {
application.beginBackgroundTask(withName: "") {}
}
And below is my ViewController class
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self;
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.allowsBackgroundLocationUpdates = true
locationManager.distanceFilter = kCLDistanceFilterNone
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didUpdateLocations \(Date())")
self.locationManager.stopUpdatingLocation()
}
}
I ran into this where a QT app would stop getting location events in the background after an hour or two.
In the App Delegate when the app would go into the background I would stop the CLLocationManager, decrease the Accuracy from kCLLocationAccuracyBest to kCLLocationAccuracyNearestTenMeters AND increase the distance filter from None to 50 meters and it would then track for 24+ hours.

Ranging iBeacons in the background

I am working on some internal location tracking, just to see how accurate it can get (not very). The app is never going on the app store
Can I just check I have done everything to enable background iBeacons updates (didRangeBeacons) to happen, it does seem to work but die 20 mins later. This could be useful to others as there seemed mixed info out there.
I am using iOS 9
Enable location updates in Capabilities
On each region enable region.notifyEntryStateOnDisplay = true
On Location Manager enable locationManager.allowsBackgroundLocationUpdates
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers (set this to save battery
Implement didUpdateLocations delegate method but you don't need to do anything here
I also implemented didUpdateToLocation delegate method just for belts and braces
Make sure you have the pList entries for Location Manager (NSLocationAlwaysUsageDescription, NSLocationWhenInUseDescription)

CLLocationManager not receiving updates in background after a while

I have an app where the user can gps-track his activities.
Everything works as expected with background GPS updates, but there are very rare cases (1 out of 1000), where I am just not receiving update calls from CLLocationManager when my app is in background. Not immediately, but after some time.
My app starts receiving updates and then all of a sudden (can be a couple of minutes or hours of tracking) it just won't get any more locations updates. It continues reporting location as soon as the app get's active again. But of course those missing locations are bad!
I didn't figure out when and why it happens, that's why I wanted to ask if somebody else already experienced the same issue? I can say that it's not a phone call or something like that that is interrupting. I also don't get callbacks in the didFail delegate method. I just don't get anything any more....
And the big problem is that I have NO IDEA on how to debug that, as I can't reproduce it on purpose.
Any help is very much appreciated.
EDIT:
Here's how I setup my location Manager
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kMinimumDistanceFilter;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.pausesLocationUpdatesAutomatically = NO;
self.locationManager.activityType = CLActivityTypeFitness;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
if ([self.locationManager respondsToSelector:#selector(setAllowsBackgroundLocationUpdates:)])
{
self.locationManager.allowsBackgroundLocationUpdates = YES;
}
and then later when the Start-Recording-Button is hit
[self.locationManager startUpdatingLocation];
EDIT 2:
If you start this service and your app is suspended, the system stops
the delivery of events until your app starts running again (either in
the foreground or background). If your app is terminated, the delivery
of new location events stops altogether. Therefore, if your app needs
to receive location events while in the background, it must include
the UIBackgroundModes key (with the location value) in its Info.plist
file.
I don't even startUpdatingLocation in the background... But it seems as if that's what happening to my app. How would I be even able to start tracking if the app is suspended? That's impossible, isn't it? Cause suspended would mean it's not executing code?!?
Do you have allowsBackgroundLocationUpdates set to YES in your Info.plist?
From documentation:
By default, this is NO for applications linked against iOS 9.0 or
later, regardless of minimum deployment target.
With UIBackgroundModes set to include "location" in Info.plist, you
must also set this property to YES at runtime whenever calling
-startUpdatingLocation with the intent to continue in the background.
Setting this property to YES when UIBackgroundModes does not include
"location" is a fatal error.
Resetting this property to NO is equivalent to omitting "location"
from the UIBackgroundModes value. Access to location is still
permitted whenever the application is running (ie not suspended), and
has sufficient authorization (ie it has WhenInUse authorization and is
in use, or it has Always authorization). However, the app will still
be subject to the usual task suspension rules.
See -requestWhenInUseAuthorization and -requestAlwaysAuthorization for
more details on possible authorization values.

Resources