swiftbluetoothbackgroundbackground-modeios-background-mode

Swift - Bluetooth write characteristic in Background


I'm developing an App in Swift 5 that connects to a wearable device that measure body information (temperature, heart rate, etc.)

For measure this information, I have to write a Data object in one characteristic of the device (and receive the information in other characteristic with notifications activated), and now i have to measure it every 30 minutes, so I have to create a timer with repeat every 30 minutes to execute that "write" in the BLE characteristic. (All the options in Capabilities are already activated - bluetooth-central, bluetooth-peripheral, background-processing, background-fetch)

I've read a lot of topics in Stack Overflow and there are people that says that you can't write to BLE in background and other that say that you can.

Before to implement all the possibilities I've read: It's possible to execute every 30 minutes a task to connect to a device, set notification to true to one characteristic, and write a Data object in one characteristic in Background Mode?

If the response is "Yes", is there any code that I have to implement apart from the corresponding bluetooth methods that already work in the foreground?

I've not attach my BLEManager class (centralManager) because is the "standard" from the Apple Documentation, but if you need, ask me and I'll attach it.


Solution

  • It's possible to use CoreBluetooth in background mode: https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html

    Note a few caveats here:

    To perform certain peripheral role tasks while in the background, you must include the UIBackgroundModes key with the bluetooth-peripheral value in your app’s Info.plist file. When this key-value pair is included in the app’s Info.plist file, the system wakes up your app to process read, write, and subscription events.

    I think you can wake the app directly with the peripheral, but scheduling probably won't work.

    Upon being woken up, an app has around 10 seconds to complete a task

    Not sure what you're trying to do, but you're time limited so keep that in mind as well.