Properly launching an iOS app into the background from a location event - ios

(iOS 11, Swift 4.1)
I wrote a cordova plugin in swift to handle region monitoring, but it isn't working properly when my app is suspended or killed. Here is my class with the relevant functions:
class GeofenceManager : NSObject, CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
switch state {
case .inside:
log ("Did Enter Region: " + region.identifier)
self.postGeofenceTransition(region: region, transitionType: 1)
break
case .unknown:
log ("Unknown Transition for region: " + region.identifier)
// self.postGeofenceTransition(region: region, transitionType: 1)
break
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
log ("Did Exit Region: " + region.identifier)
self.postGeofenceTransition(region: region, transitionType: 2)
}
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
log("Did start monitoring region: " + region.identifier)
self.locationManager.requestState(for: region)
}
}
(I do it this way to handle someone that's already in the region when we start monitoring)
I've also got "didChangeAuthorizationStatus" that fetches and sets all the geofences, that is working fine.
In my AppDelegate (objc) I'm attempting to start Location Services if the app is opened from a region event, with
if([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
_locationManager = [[CLLocationManager alloc] init];
[_locationManager setDelegate:self];
[_locationManager setDistanceFilter:kCLHeadingFilterNone];
//change the desired accuracy to kCLLocationAccuracyBest
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//SOLUTION: set setPausesLocationUpdatesAutomatically to NO
[_locationManager setPausesLocationUpdatesAutomatically:NO];
[_locationManager startUpdatingLocation];
}
My question is, if my app is opened from an event, i.e. "didEnterRegion", I immediately start location services, but will I hit my "didEnterRegion" delegate again? And am I doing something wildly wrong here?
I think I'm missing some understanding of iOS application states, have dug into the docs but it hasn't clicked yet. Any insight is very appreciated.

My question is, if my app is opened from an event, i.e. "didEnterRegion", I immediately start location services, but will I hit my "didEnterRegion" delegate again?
If your app was suspended or terminated, and if it is awakened or launched just to receive didEnterRegion, it stays in the background. It is given time just to handle this one event and then it is suspended.
You cannot start location updates with startUpdatingLocation at that point. You are in the background! Even if you are authorized for background updates, you cannot start getting updates while you are in the background. And even if you could, your code would fail, because you never set allowsBackgroundLocationUpdates. And even if you could do that, you wouldn't get any events, because you have no implementation of didUpdateLocation.
The correct procedure is: do nothing. Just handle didEnterRegion and get out. If the user enters the region again, your didEnterRegion will be called again. Region monitoring just goes on forever until you stop it (and make sure you do stop it, or the user may be be forced to delete your app).
Addendum: How to respond to being launched from scratch in the background like this? You can detect the key in didFinishLaunchWithOptions and handle it there and return false, or you can ignore it and return true and receive didEnterRegion. But either way you must immediately create a location manager and appoint its delegate or you will get nothing, obviously. This is why you should always create the location manager and set its delegate in your app delegate or root view controller, something that always exists, and exists as early as possible in the life of the app, as soon as it launches.

Related

Are there any other solutions in Monitoring BeaconRegion Immediately?

I make an application with iBeacon.
And I decide to use CoreLocation and Ranging.
But, I think Ranging use too much energy.
As an alternative to Ranging, I tried to use Monitoring.
Then, I profile Ranging's usage energy level and Monitoring's usage energy level.
Ranging use about 2 energy usage levels more than Monitoring
Result: (Ranging's level: 10/20, Monitoring's level: 8/20)
But, Monitoring doesn't called didExit or didDetermineState immediately.
I want My app has a Real-Time as Ranging.
My Solution:
Monitoring Start
If I enter Monitoring region, I start Ranging
If I exit region, ranging result is nil, and stop Ranging
Monitoring Stop and Start.
Monitoring doesn't called exit or determineState method immediately.
But, I discovered stop and rerun monitoring make my application has Real-Time.
I think that solution reduce energy usage when standby.
And It Actually Working!
▼ Here is my Code.
class Service: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, CLLocationManagerDelegate{
private let constraint = CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor)
private let region = CLBeaconRegion(beaconIdentityConstraint:
CLBeaconIdentityConstraint(uuid: Constants.beaconUUID!,
major: Constants.beaconMajor,
minor: Constants.beaconMinor),
identifier: Constants.beaconIdentifier)
var locationManager: CLLocationManager!
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
}
extension Service {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if manager.authorizationStatus == .authorizedAlways {
region.notifyOnExit = true
region.notifyOnEntry = true
region.notifyEntryStateOnDisplay = true
manager.startMonitoring(for: region)
}
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == .inside {
didEnterEvents(manager)
}
}
func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
if beacons.first == nil {
didExitEvents(manager)
stopAndRerunMonitoring(manager, for: region)
}
}
}
extension Service {
private func stopAndRerunMonitoring(_ manager: CLLocationManager, for region: CLRegion) {
print("reboot!")
manager.stopMonitoring(for: region)
manager.startMonitoring(for: region)
}
private func didEnterEvents(_ manager: CLLocationManager) {
print("inside")
manager.startRangingBeacons(satisfying: constraint)
}
private func didExitEvents(_ manager: CLLocationManager) {
print("outside")
manager.stopRangingBeacons(satisfying: constraint)
}
}
I know my solution is terrible.
But I can't find any other solution.
Plz, Can you find any other better solution?
etc:
didEnter and didExit called determineState method.
I need to call requestState() method in other code. so I write a Enter event logic in determineState method.
You need Real-Time?
Yes, because i will make safety system with beacon. So My application's requirements has Real-Time.
I need Real-Time regioning and less energy usage.
The approach you describe of starting ranging on region entry and stopping it on region exit is not "terrible". It is in fact quite common. It is often used to determine the exact identifiers of the beacons detected, which would otherwise not be possible by monitoring alone.
For your use case, it is also true that ranging while inside a region will expedite the region exit event, because it forces a constant Bluetooth scan rather than relying on the slower hardware filters used for monitoring. While ranging is active, region exits come 30 seconds after the beacon was last detected.
For this to be a practical solution, you must take into account background behavior:
Unless you do special tricks, iOS won't let you range for more than a few seconds when the screen is off. As soon as ranging stops, you lose the expedited region exits.
While the screen is on, there is no point in saving battery by not ranging all the time, because the illuminated screen uses over 100x as much battery as the constant Bluetooth scan of ranging.
To get any benefit from the technique you describe, you must extend the ranging time in the background as described in my blog post here. Be aware that since I wrote that article, Apple has reduced the time you can extend ranging in the background from 180 seconds to 30 seconds, which may not be enough for your needs. You can get unlimited background ranging by:
Add the location background mode to Info.plist
Obtain "always" location permission from the user. It is not sufficient to get "when in use" permission.
Start a background task as described here: http://www.davidgyoungtech.com/2014/11/13/extending-background-ranging-on-ios
Request 3km location updates from CoreLocation. This will keep the app running in the background without extra battery drain from GPS, as 3km accuracy only uses the cell radio You don't need to do anything with these results. You just need to request them to keep the app alive.

Is this possible to activate app in terminate state if user enter into any region - iOS

I have implemented geofencing functionality in my App.
I get notified when user enter into particular region with below method
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
handleEvent(forRegion: region)
}
}
Above method is calling even in terminated state.
Is there any way to relaunch or activate application in terminated
state if enter into the region.

Receiving Location even when app is not running in Swift

Still very new to Swift. I have come from an Android background where there is BroadcastReceiver that can deliver location info to a service even though the app isn't running.
So I was looking for something similar in iOS/Swift and it appears that before this wasn't possible but it may be now. I am developing for iOS 10 but would be great if it was backwards compatible.
I found
startMonitoringSignificantLocationChanges
which I can execute to start delivering location updates, although this raises a few questions. Once I call this and my app is NOT running, are the updates still being sent ? And how would the app wake up to respond ?
Also restarting the phone and when it return, does this mean I still need call startMonitoringSignificantLocationChanges again meaning that I would have to wait for the user to execute my app. Or does it remember the setting after reboot ?
Still a little confused how to get around this, here's a brief explanation of what I am trying to do.
I would like to update the location of the phone even though the app is not running, this would be sent to a rest service every so often.
This way on the backend services I could determine if somebody is within X meters of somebody also and send them a push notification.
It may or may not be a good solution but if I were you I would have used both startMonitoringSignificantLocationChanges and regionMonitoring.
Here is the sample I made which worked well with iOS 13.
Lets take regionMonitoring first. We have certainly no problems when the app is in foreground state and we can use the CLLocationManager's didUpdate delegate to get the location and send it to the server.
Keep latest current location in AppDelegate's property, lets say:
var lastLocation:CLLocation?
//And a location manager
var locationManager = CLLocationManager()
We have two UIApplicationDelegates
func applicationDidEnterBackground(_ application: UIApplication) {
//Create a region
}
func applicationWillTerminate(_ application: UIApplication) {
//Create a region
}
So whenever the user kills the app or makes the app go to background, we can certainly create a region around the latest current location fetched. Here is an example to create a region.
func createRegion(location:CLLocation?) {
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
let coordinate = CLLocationCoordinate2DMake((location?.coordinate.latitude)!, (location?.coordinate.longitude)!)
let regionRadius = 50.0
let region = CLCircularRegion(center: CLLocationCoordinate2D(
latitude: coordinate.latitude,
longitude: coordinate.longitude),
radius: regionRadius,
identifier: "aabb")
region.notifyOnExit = true
region.notifyOnEntry = true
//Send your fetched location to server
//Stop your location manager for updating location and start regionMonitoring
self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoring(for: region)
}
else {
print("System can't track regions")
}
}
Make use of RegionDelegates
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("Entered Region")
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("Exited Region")
locationManager?.stopMonitoring(for: region)
//Start location manager and fetch current location
locationManager?.startUpdatingLocation()
}
Grab the location from didUpdate method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if UIApplication.shared.applicationState == .active {
} else {
//App is in BG/ Killed or suspended state
//send location to server
// create a New Region with current fetched location
let location = locations.last
lastLocation = location
//Make region and again the same cycle continues.
self.createRegion(location: lastLocation)
}
}
Here I have made a 50m region radius circle. I have tested this and it is called generally after crossing 100m from your center point.
Now the second approach can me using significantLocationChanges
On making the app go background or terminated, we can just stop location manager for further updating locations and can call the startMonitoringSignificantLocationChanges
self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoringSignificantLocationChanges()
When the app is killed, the location is grabbed from didFinishLaunching method's launchOptions?[UIApplicationLaunchOptionsKey.location]
if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
//You have a location when app is in killed/ not running state
}
Make sure to keep BackgroundModes On for Location Updates
Also make sure to ask for locationManager?.requestAlwaysAuthorization() by using the key
<key>NSLocationAlwaysUsageDescription</key>
<string>Allow location</string>
in your Info.plist
There can be a third solution by taking 2 LocationManagers simultaneously.
For region
Significant Location Changes
As using significantLocationChanges
Apps can expect a notification as soon as the device moves 500 meters
or more from its previous notification. It should not expect
notifications more frequently than once every five minutes. If the
device is able to retrieve data from the network, the location manager
is much more likely to deliver notifications in a timely manner.
as per the give Apple Doc
So it totally depends on your requirements as the location fetching depends on many factors like the number of apps opened, battery power, signal strength etc when the app is not running.
Also keep in mind to always setup a region with good accuracy.
I know that this will not solve your problem completely but you will get an idea to move forward as per your requirements.

How does one call a function from ViewController in AppDelegate?

I am making an app that uses iBeacon. When the iBeacon is detected (inside AppDelegate), the app detects the phone's coordinates and forwards them to an API.
I have a function called runGPS() set up in ViewController which does the above and am trying to get it to execute when the iBeacon is detected.
When I do ViewController().runGPS(), I get an error: Missing parameter for 'coder' in call
I've looked up this issue and keep going around in circles on resolving it. One correction leads to another error etc. etc. etc.
How does one correct this or is my overall strategy for this wrong?
func locationManager(manager: CLLocationManager,
didEnterRegion region: CLRegion) {
manager.startRangingBeaconsInRegion(region as! CLBeaconRegion)
manager.startUpdatingLocation()
NSLog("You entered the region")
ViewController(NSCoder)!.runGPS()
}
I have also implemented iBeacon in my application. You have to add this location manager delegate in that viewcontroller and set delegate there like
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
and you can check in viewController if any user enter to your beacon region then this delegate method will run
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
}
you can check your beacon in beacons array received in parameter.
You should separate out the runGPS() code from the ViewController class if its not meant to be there. Is it using any of the ViewController's functionality? If not then you should move it to a separate class meant for passing data to API. If you cannot do that then you can declare runGPS as a static method and called ViewController.runGPS() provided you are not using any of the properties of the ViewController in runGPS() method

Beacon Ranging in the Background on iOS

I'm currently trying to find a way to range beacons in the background in iOS by using location monitoring and then triggering the ranging like so:
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
if (state == .Inside) {
locationManager.startRangingBeaconsInRegion((region as? CLBeaconRegion)!)
}
}
I'm then trying to get an API call to be made in the beacon ranging
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
for beacon in beacons {
let minor = beacon.minor as Int
let major = beacon.major as Int
do {
try APICall.canSeeBeacons(major, minor: minor)
} catch {
print("Error making API call")
}
}
}
However this only works for about ten minutes while the phone is in the background, after ten minutes it no longer works but I'm hoping to make it continuous so that API calls can always be made when a beacon is found. I do also have the correct keys set in the permissions and I'm using requestAlwaysAuthorization() on my locationManager
Take a look on the Apple's iOS Dev Library regarding Background Executions:
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
If the type of your app is one of the accepted types for longer background executions, add the key Required background modes to your Info.plist with an array, containing one or more of the enabled types: audio, location, voip, newsstand-content, external-accessory and/or bluetooth-central.
Just note that this will be reviewed by Apple before publishing your app on the App Store.
EDITED:
I didn't use this for a while, but tested now and it seems it's even easier since Xcode 6.
Follow the steps:
1. Add the key Required background modes to your Info.plist
2. Go to Capabilities
3. Select the background mode(s) that fit.
I had the same problem. As said a commentator I've moved location manager delegate methods into the App Delegate. And also I added this:
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
And it works.

Resources