I have been searching for days now on this subject. I have seen a few posts but none of the implementations work, or, they mention deprecated methods, options or Libraries that are private. I find Apple docs to be the worst thing of all time and yet even in that debacle wall of text known as their docs I found a few references to launching a terminated application based on entering the range of an iBeacon.
What I need is to have the app be fully closed and terminated as though the user is completed and finished with it. Then I need to use the UIBackgroundMode
for BLE services in info.plist
for listening to the didRangeBeacons
delegate method. It fires, so I know that much is working.
It's at this point that all implementations so far have failed. How on earth do you launch the app to even a backgrounded state from being in range of an iBeacon? I am beginning to think all you can do is trigger a local notification when in range...
Getting an app to auto-launch from a not-running state based on iBeacon detection is surprisingly easy with
CoreLocation
and iBeacon.In order for it to work a few pre-requisites must be met:
CLBeaconRegion
withCLLocationManager
by callinglocationManager.startMonitoring(region: region)
, and set thelocationManager.delegate
. Since you also want to range, you can simultaneously callstartRanging(beacons: beacons, region: region)
. It is usually easiest to do this in yourAppDelegate.
If you do all of the above correctly, then iOS CoreLocation will remember that your app has registered the
CLBeaconRegion
and auto launch your app on beacon detection. Even if you reboot the phone, or kill your app from the task switcher it will do this. After auto launching your app into the background, it will call thedidEnter(region: region)
callback on your delegate and then start calling thedidRange(beacons: beacons, region: region)
callback once per second for about 10 seconds, until the operating system will once again suspend your app.There are lots of ways to make mistakes when testing so this doesn't work. But if you do everything right, this is pretty darn reliable.
What you can't do is bring the app to the foreground programmatically, because iOS does not allow this. On iOS, a user must gesture to bring an app to the foreground -- this is nothing to do with beacons, but a long-standing rule in the design of the OS. This is why many apps send a local notification while they are in this brief background state after detecting a beacon to give the user a way to bring the app to the foreground.