Managing Duplicate BLE Notifications on iOS App Re-launch

52 views Asked by At

I am developing a Swift application that interfaces with an ESP32 device over BLE, utilizing the Nimble stack for communication. The application subscribes to characteristic notifications from the ESP32, which are received consistently at one-second intervals.

The issue arises when I redeploy my app with new code, leading to multiple instances of the same notification being received - duplicates on the second launch, triplicates on the third, and so on.

This behavior seems to stem from the repeated execution of the following line within the didDiscoverCharacteristicsFor delegate method:

peripheral.setNotifyValue(true, for: datamapCharacteristic)

I attempted to mitigate this by checking the isNotifying property before setting the notification:

if !datamapCharacteristic.isNotifying {
    peripheral.setNotifyValue(true, for: datamapCharacteristic)
}

However, this approach fails because isNotifying resets to false when the app is relaunched, despite the ESP32 still sending notifications.

Persisting the notification state in UserDefaults is not a viable solution either. If the app is terminated and the ESP32 is reset, the notification subscription is indeed lost, which leads to an inconsistent state.

Could anyone advise on a robust method to prevent this duplication of notification registrations, or suggest an alternative approach to handle BLE notifications when the app restarts after a code update?

Thank you for your insights.

0

There are 0 answers