How to do BG NW download after geofence didEnterRegion/didExitRegion notice - ios

I am developing a client/server app for a client where the clients are iOS devices.
One client module is for traveling salespeople.
My client wants the salesperson's app to automatically download it's local database when the salesperson leaves the office, and when the salesperson returns to the office.
I am setting up a geofence using the location manager's startMonitoringForRegion method, and will look for the UIApplicationLaunchOptionsLocationKey on launch, as well as looking for calls to the location manager locationManager:didEnterRegion/locationManager:didExitRegion methods from the background.
My question is, how do I ask the system to allow me time to make a network connection and download new data in response to either an app launch with a UIApplicationLaunchOptionsLocationKey, or background calls to locationManager:didEnterRegion/locationManager:didExitRegion?
None of the background mode keys (UIBackgroundModes) look like the right fit.
I don't need the location key, since I don't need live location information, just geofence enter/exit messages. The fetch key isn't what I need either, since that causes the system to wake my app up in the background at times it chooses.
Do I have to have one of the background mode keys set in order to make a beginBackgroundTaskWithExpirationHandler call?
I guess what I should do is submit my network request in my beginBackgroundTaskWithExpirationHandler in my locationManager:didEnterRegion/locationManager:didExitRegion methods. Will the system allow me to do that without having a UIBackgroundModes key set?
And can I make a call to beginBackgroundTaskWithExpirationHandler if I'm already running from the background? (In the case where the app is running but not frontmost and a locationManager:didEnterRegion or locationManager:didExitRegion call comes in.) My goal is to ask for enough background time to process my network download and save the data to my local database.
Any guidance from somebody who's done something like this would be a big help. The docs are pretty vague, and figuring out how to use the background APIs by trial and error is likely to be pretty time-consuming.
P.S. I'm developing this app in Swift, although I'm a longtime Objective-C developer. I'm comfortable translating Objective-C to Swift or mixing Objective-C and Swift as needed, so examples in either language would be useful.

It is OK to call beginBackgroundTaskWithExpirationHandler from background. As of iOS8 this call will extend your run time to 180 seconds from 10s.
Keep in mind that you need to request Always authorization for location services, that's what is required to run region monitoring.
I suggest you do use the background location key. I forgot to set it in one of my apps, and it still was receiving the region enter/exit events. However,
-- the behavior might change with minor iOS upgrade, and also
-- the app might be rejected by Apple

Related

React Native iOS app restart on reboot

I want to create an iOS app using React Native. One of the primary features of the app is that it runs constantly in the background. It also requires using GPS btw (in case that is important).
I have had a number of devs tell me its not possible to do this for iOS, however I have read that it is do-able.
Is this possible to do in the iOS environment? Mainly, if the app is running when the phone is powered off, can you make it open when the device is restarted without the user opening it?
I should say that I am a RN novice and any help is much appreciated.
If your app gets permission to get location while it's not in the foreground, then you will get periodic updates and some time to process it.
For example, if you are giving driving directions.
https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW10
If there is no good user benefit for you to get the location in the background constantly, you might be rejected. Apple suggests region monitoring instead
iOS supports the delivery of location events to apps that are suspended or no longer running. The delivery of location events in the background supports apps whose functionality would be impaired without them, so configure your app to receive background events only when doing so provides a tangible benefit to the user. For example, a turn-by-turn navigation app needs to track the user’s position at all times and notify the user when it’s time to make the next turn. If your app can make do with alternate means, such as region monitoring, it should do so.
I have no idea how RN wraps this behavior, but no matter what it does (or what a plugin might do), the core iOS behavior is how it is described in that URL.
I verified yesterday (at least on iOS 11.2 simulator) that automatically restarting the app (and the location tracking) after phone reboot works.
The key point is that startMonitoringSignificantLocationChanges needs to be on to wake up the app after reboot. For me the difficult part was figuring out when to turn it on, because I couldn't find a reliable way to detect when the phone is being rebooted or run any code at that point. However, based on initial testing it looks like startMonitoringSignificantLocationChanges is independent and doesn't negatively impact the usual location updates, so now I just leave it on all the time and toggle startUpdatingLocation / stopUpdatingLocation on top of it based on Core Motion-detected activity.
Otherwise requirements are the same as for any location tracking on the background, i.e. handle permissions and don't process too much. Apple documentation explains how to detect that the app was relaunched by a location event.
Here's a react native module which basically helps you achieve what you're describing: https://github.com/transistorsoft/react-native-background-geolocation

How does iOS Google Map detect I am entering a car?

The latest iOS Google Map application(currently of version 4.9.0) has a very nice feature, but so far I can not figure out how this is possible.
The feature is: whenever I am entering my car, try to drive somewhere, Google map will send me a notification to my phone, guess where I am going, giving me an estimate of the traffic, even when the phone is in locked state, and the Google map app hasn't been used for days. A screenshot is provied as following:
This is quite amazing to me as an iOS developer. How can it live in the background and detect I am entering a car with such accuracy?
One of my guess is, Google map is using significant location change API. By using this way, the app can be waken in background mode, but, there is still no guarantee it is waken when I am entering my car. And I have already written a test app using this mechanism, although it can be waken in the background, but the timing is not correct, failed to detect I am entering a car or not.
CLLocationManager Class Reference
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 UIApplicationLaunchOptionsLocationKey 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.
Any suggestion and help appreciated.
One comment from #alexkent points out my mistake. This is Apple's Maps.app, not Google Maps. All credits belongs to #alexkent.
That notification is from Apple's Maps.app not Google Maps. A new
feature in iOS9 (which you must be running) is the ability to detect
when you are in your car. I imagine this is done by detecting the
Bluetooth signal from the car radio (I have not checked this). I do
not believe there is developer API available for this feature.
#alexkent is right. It works using bluetooth and there is no public API for that. If you close your bluetooth this stops happening.
Geofencing and in general Geolocation accuracy is not that granular.

Call web service even if ios app is in background

In my application I need to log user status every 15 minutes. Is it possible if the app is in background (not killed)??
Currently I enables the Background location update. But how to call in each and every 15 minutes
While other answers are correct about background fetch, there is also another background option called VoIP, which apps like Skype use. In this case OS will wake up your application more frequently (even every 10 minutes if I remember correctly) and you can keep pinging your server in background. The obvious down side is that your app must have Voice over IP functionality, otherwise it would get rejected on the App Store.
All you need to do is add call setKeepAliveTimeout:handler: method and have voip enabled in background capabilities.
Just adding this for the sake of completion.
You may want to look at the Background Fetch capabilities added in iOS7 and beyond:
http://www.appcoda.com/ios7-background-fetch-programming/
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html (Search for background fetch)
You won't be able to control the interval to exactly 15 minutes but you will find that this mechanism is the closest Apple will allow.
It is not possible to perform network calls at clearly specified intervals when your app is in background mode. You can tell your app to use background fetches
This article gives a great overview on the capabilities that you can do with this API. Basically it allows you to tell iOS that your app wants to perform networking calls in the background, however you can't exactly control when and how often iOS the network calls are going to be performed. iOS will schedule your network calls for you, and depending on how your app is used it will adopt the frequency with which it performs the requests. Documentation can be found here.

HTTP request in case of didEnterRegion, didExitRegion

I am a little bit confused about this question.
Somewhere I read, it is not allowed by Apple to make network requests, when an app not in the foreground. Is also the case, when app is woken up by locationManager events?
What I'd like to: define a Beacon region, handle locationManager:didEnterRegion: and locationManager:didExitRegion: to call my simple web service methods. It should be done even if the app is not active and woken up by location manager.
Technically it is easy to implement - basically, I have already made it - but I don't know if it is allowed by Apple, and would take app review successfully.
Thanks!
Yes, it is allowed. It is a common technique, and I have several apps in the AppStore that do this. The Beacon Scavenger Hunt, for example, sends stats back to our server when participants use the iOS app to find beacon targets in the hunt.
When you detect a beacon in the background, however, you only have about 5 seconds of running time from iOS. Take care that your server responds quickly enough. This small time window is the way Apple enforces that people don't abuse this.

Processing network calls from background. Is it allowed by Apple?

We are working in a groupon-like app where alerts are displayed to the user when he/she enters in the range of an offer.
The client insists on having alerts even when the app is in the background.
Due to the architecture of the system, the app gets the location of the client at intervals and checks with the server if there is any new alert. If so, the app does some processing in the local database and displays a notification.
APN cannot be used since changes in the server are out of reach for this project.
My question is whether Apple would accept it in AppleStore as I have read different opinions about it and Apple discourages its use as in this extract from iOS Developer Library
http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html
At wake-up time, your app is put into the background and given a small amount of time to process the location data. Because your app is in the background, it should do minimal work and avoid any tasks (such as querying the network) that might prevent it from returning before the allocated time expires. If it does not, your app may be terminated
Thanks
How often does your app get location from the user? According to Apple's Background Execution and Multitasking, if you are getting the location updates on a regular schedule (I think it's less than 10 minutes), your app can still process in the background if you add location to UIBackgroundModes in your info.plist. With those CLLocation coordinates, you can then process your web service requests.
I personally have not done something like this, so I can't tell you for sure if Apple will reject your app or not. However, if everything is within the guideline and requirements set by Apple, I don't see why they would reject your app.
EDIT:
From the Apple doc:
An app that provides continuous location updates to the user (even
when in the background) can enable background location services by
including the UIBackgroundModes key (with the location value) in its
Info.plist file. The inclusion of this value in the UIBackgroundModes
key does not preclude the system from suspending the app, but it does
tell the system that it should wake up the app whenever there is new
location data to deliver. Thus, this key effectively lets the app run
in the background to process location updates whenever they occur.
I guess even if the app is suspended, it will wake up whenever there is a new location data to deliver.
I think you should reconsider your approach for this application. It sounds like you have decided to build a set of features which are not necessarily well informed by, or a good fit for, the characteristics of the devices the app will run on.
You write that "the app gets the location every n minutes" but that's not how iOS location services work. Querying location services for the current location occasionally is a good approach when your app is running in the foreground but that's not an option once it is suspended or terminated. Instead you need to subscribe to location events, at some level of accuracy, and your app will be notified when the device's location changes. There are no guarantees about the schedule on which you receive these events and it varies depending on the accuracy you request and the speed at which the device is moving.
Additionally, obtaining a location is an expensive operation and can quickly drain the device's battery. Burning through a user's available battery power in an hour or two is a very good way to get your app uninstalled quickly. Where possible you should be using the significant location change service to get low accuracy location updates with minimal power consumption. If you need more precision then consider using boundary crossing events for a defined region or at least reduce the accuracy your have requested as much as possible.
With all that out of the way you still need to work within the limited time your app has to run once started by a location update. That's probably not long enough to make a round trip to the server. If a network connection is already active and the device happens to have low latency you will probably get a response some of the time but I would expect to see the app terminated by the OS frequently. When that happens I don't know that you will continue to receive location updates which might otherwise re-launch the app.
Instead of downloading a list of alerts and displaying them locally a better solution might be to attempt to send your current location to the server via UDP when you see a significant location change. That way you can fire off a network request without waiting for a response. Only some of those requests will still succeed but at least your app won't be terminated. You can then process the locations you receive on the server and send push notifications when appropriate.
I realize that you don't seem to be able to make server side changes. In that case the best you might be able to do is pre-fetch alerts for the nearby region when the app runs (and if you ever manage to complete a round-trip while in the background). That way you could compare location updates to that list and not need to fire off a network request on every location update. Unfortunately it sounds like you might be backed into a corner here with no reliable solution available under your current constraints.

Resources