How to ensure background execution after loosing bluetooth connection in the background

Hi there


I've read many posts about running tasks in the background, however I have not been able to get an answer to our bluetooth entitled app's problem.


We have an app that connects to a bluetooth device and sends and receives BLE data in the background. There is no problem when the connection is present, the problem we face is when the connection is lost, we want to attempt to reconnect to the device. Here is where it gets difficult: We no longer have the Bluetooth entitlement to continue executing in the background. Yet it is extremely important that our app is not suspended to send the user a local notification after 20 seconds that the critical connection was lost.


We start a task with beginBackgroundTask, however if the screen is locked, it appears the background execution request to send a local notification after 20 seconds is not respected at all. I dont even see a expiryHandler of our backgroundTask being called. We can execute if the timer is set to 5 seconds, but no longer.


We cannot go the route of push notifications, as our app may not be connected to the Internet. Yet, our app is extremely critical that it can alert the user, after 20 seconds.


How do I request that the OS gives our app 20 seconds to execute this background task?

Replies

One recommendation I have for Bluetooth in the background is overriding the DisconnectedPeripheral delegate with a call to connect to the peripheral (the peripheral object is in the parameters of the delegate). ConnectPeripheral doesn't have a timeout and will connect to the Bluetooth device if it's within range. The Core Bluetooth delegates will also process in the background regardless of your execution time. This will at least keep your connection open and you can continue your Bluetooth work.


"In addition, new data arriving from the peripheral causes the system to wake up the app so that it can process the data. The system also wakes up the app to process accessory connection and disconnection notifications. "


https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html


As far as asking for extra time, I believe you're a bit out of luck. The background thread will be suspended until the user decides to re-open the app. You'd need something to wake the app up again, detect that it didn't finish bluetooth work, and then display the notification (perhaps by using Background Fetch?)