问题
My Application works with continuous background location updates. Of course it has all the permissions and other stuff like
allowsBackgroundLocationUpdates = true
Initially I wanted to react to LowPowerMode
changes while in background using NSProcessInfoPowerStateDidChange
notification. And to disable allowsBackgroundLocationUpdates
to stop updating locations without calling stopUpdatingLocation
.
However, I found out that after receiving the notification and setting
allowsBackgroundLocationUpdates = false
in background application is going on working.
So I went farther and identified, that disabling allowsBackgroundLocationUpdates
even in foreground after it was initially set to true
doesn't work at all. Application continues working in background.
Apple's documentation on the matter
you use this property to enable and disable the behavior based on your app’s behavior
From the CLLocationManager class, description of allowsBackgroundLocationUpdates
property
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. Resetting this property to NO is equivalent to omitting "location" from the UIBackgroundModes value.
Simple project on GitHub that shows the behavior I mentioned.
So the question, is it intentional behavior of the property?
回答1:
When the value of this property is false, apps receive location updates normally while running in either the foreground or background based on its current authorization. Updates stop only when the app is suspended, thereby preventing the app from being woken up to handle those events.Apple API Discussion.
I think the property discussion can solve your problem.
回答2:
Despite it's maybe misleading name, it looks like requestWhenInUseAuthorization() gives you the behaviour you want (like @zhongwuzw said).
From the documentation:
If the user grants “when-in-use” authorization to your app, your app can start most (but not all) location services while it is in the foreground. (Apps cannot use any services that automatically relaunch the app, such as region monitoring or the significant location change service.) When started in the foreground, services continue to run in the background if your app has enabled background location updates in the Capabilities tab of your Xcode project. Attempts to start location services while your app is running in the background will fail.
If you need the "always" permission (or the user grants it without you asking for it through the Settings app), I found that stopping and immediately re-starting the location manager forces allowsBackgroundLocationUpdates
to take effect.
来源:https://stackoverflow.com/questions/41704302/disabling-allowsbackgroundlocationupdates-cllocationmanager-doesnt-work-after