Best Way to Use Background Location Updates in iOS (Swift)

Background Location Updates

@onurgenes, If you add a real code from your project, first of all, how you can start any location updates from here?

    if let _ = launchOptions?[.location] {
locationManager = LocationManager()
locationManager?.delegate = self
locationManager?.getCurrentLocation()
return true
}

When app start at for the first time launchOptions will be nil, and your LocationManager() even not started, so your any location monitoring and updates will not work (maybe you have the some code at app.start() but now it looks like an error).

The second thing - at your sample, you are using bought of locating monitoring:

    locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()

so here your location manager handles only significantLocationChanges(). If you want to use both of them - you should toggle it (at didBecomeActiveNotification and didEnterBackgroundNotification) or create different instances of the location manager as Apple recommend.

The third - your problem. Let's look for this part more detailed:

locationManager = LocationManager()
locationManager?.delegate = self
locationManager?.getCurrentLocation()

As I mention up - at LocationManager() you start monitoring location:

locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()

and this is what you need - significant location changes. But after you call getCurrentLocation() with locationManager.startUpdatingLocation() so you 'rewrite' your monitoring, and that's the reason why you did not get any updates from it.

Also, take in mind:

  1. Significant locations deliver updates only when there has been a
    significant change in the device’s location, (experimentally
    established 500 meters or more)
  2. Significant locations very inaccurate (for me sometimes it up to 900 meters). Very often significant location use just for wake up an application and restart
    location service.
  3. After your app wake up from location changes
    notification, you are given a small amount of time (around 10
    seconds), so if you need more time to send location to the server
    you should request more time with
    beginBackgroundTask(withName:expirationHandler:)

Hope my answer was helpful. Happy coding!

Update location in Background

Couple of things to be changed.

Step 1:

Make sure you have enabled location updates background mode in capabilities section of your project as shown below

enter image description here

Step 2:

And when I'm killing the app location update against stoped.

Quoting from apple docs

If you start this service and your app is subsequently terminated, the
system automatically relaunches the app into the background if a new
event arrives. In such a case, the options dictionary passed to the
application(:willFinishLaunchingWithOptions:) and
application(
:didFinishLaunchingWithOptions:) methods of your app
delegate contains the key location to indicate that your app was
launched because of a location event. Upon relaunch, you must still
configure a location manager object and call this method to continue
receiving location events. When you restart location services, the
current event is delivered to your delegate immediately. In addition,
the location property of your location manager object is populated
with the most recent location object even before you start location
services.

link : https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

important thing to notice in above statement is

Upon relaunch, you must still, configure a location manager object and
call this method to continue receiving location events.

Meaning, your current location manager will not be of much use and you should create a new one and configure the new instance and call startMonitorSignificantLocationChanges again.

So iOS will send location updates to terminated apps only when you use startMonitoringSignificantLocationChanges.

All that are applicable only if your app was terminated and iOS relaunched it on receiving location update. But if your app is simply in background you need not do any thing on using startMonitorSignificantLocationChanges

on the other hand startUpdatingLocation will work only when app is in background/foreground mode. iOS will stop updating location if your app gets suspended or killed.

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.

link: https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation

So modify your code

 locationManager.startMonitoringSignificantLocationChange()

Ok that was about proper usage of startMonitoringSignificantLocationChanges and startupdatinglocation. Now timer for mistakes in your code.

Mistake 1:

self.bgtimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.bgtimer(timer:)), userInfo: nil, repeats: true)

Using timer to get timely updates on location. Thats not how it works!!! You cant run Timer forever. Timer stops as soon as your app suspends or gets terminated. Location Manager informs the app when location changes and you should rely on that only. You cant run timer to timely check location updates. It won't run in suspended or terminated state.

Mistake 2:

  func updateLocation() {
locationManager.startUpdatingLocation()
locationManager.stopUpdatingLocation()

Why start and stopping update locations in subsequent statements? That does not make much sense.

Mistake 3:

func StartupdateLocation() {
locationManager.delegate = self
locationManager.startUpdatingLocation()

Your StartupdateLocation gets called multiple time and every time you called this method you are repeatedly calling startUpdatingLocation on same instance of location manager. You need not do that! You can call startUpdatingLocation or startMonitoringSignificantLocationChange only once.

Best way to use background location updates in iOS (Swift)

that sends the user's location via API every 3 or 5 minutes, while the
app is backgrounded

Does not make much sense. What if user stands in same location for 5 minutes? you will make same location entry in your server multiple times? Isn't it better rather than updating location at certain interval, if you could update your server with user location once user's location changes??

So use locationManager, set its delegates and start updating your server via API when user location changes rather than at regular interval.

I don't know which is the best way to do this, or if it's even
possible because of Apple's strict background rules

Its absolutely possible. All you have to do is to opt for Location Updates capability in Xcode.

Now whats the best way? Its a relative term. This depends on how your app will use the users location info. If you unnecessarily start observing users location, you will unnecessarily drain the users iPhone battery, hence apple will reject your app.

How apple process's app using location update capability?

Its pretty simple. Location updates capability comes with the cost, that if your app observes user location updates accurately in background, it will drain out the device battery. Because its a costly trade off, apple expects you to use this only if its necessary for your app.

For example : If you are making a map app or an app that tracks the users location changes and then later plots on a map or something and lets the user know about his movement (like running apps) its absolutely fine to use location update capability because you are adding value to user.

If you try to think creepy! and try to use the location update just to keep your app alive and do some thing completely unrelated to location update in background app will reject your app. Like few developers try to be over smart and use location updates to keep their app in sync with server or to upload/download files at regular interval or something like that which are no way related to location updates, apple will reject such apps.

So no way to be creepy? And use location updates to do something useful which is not related to location itself?

Yes, you can. Apple is generous enough to allow that. For example : Dropbox uploads your images in background, when you move from one location to another. All it does is, it looks for user location changes, once location changes delegates triggers, creates a upload task with background session and starts uploading files.

How to do that?

You can still use the location manager. All you have to do is to use

locationManager.startMonitoringSignificantLocationChanges()

This will trigger your location delegates only when there is a significant location changes :)

On the other hand, if your app actually makes use of user locations and use

startLocationUpdates()

make sure you dont consume location updates unnecessarily. Make sure u put distance filter properly according to your apps requirements. Dont be greedy and dont waste iOS resources unnecessarily and apple will be happy and will not trouble you :)

Conclusion:

If your app actually makes use of location and adds some value to user (like map app/running apps/travel apps) only then use startLocationUpdates and use distance filters properly (optional, but good to have it).

If you are being creepy always use startMonitoringSignificantLocationChanges else app is bound to get rejected

continuous iOS location updates in background

You have to add this in your plist :

<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>

add this

locationManager.allowsBackgroundLocationUpdates = true

How much time update location in background mode

If you have background location updates enabled and "always" location permission and you have enabled location updates prior to your app entering the background then your app will continue to receive location updates indefinitely.

You only have a few seconds to process each update, but that should be plenty of time to send a short transaction to your server.



Related Topics



Leave a reply



Submit