Your app has to be running in the background to do something, but that is OK, because Core Bluetooth background mode will take care of that for you.
First, you need to select "Uses Bluetooth accessories" background mode in your project.
Now, your program flow will be something like this:
- Your user runs your app which scans for available doors and displays them to the user
- Your user selects a door that they want to connect to
- You save the identifier of the selected peripheral somewhere like NSUserDefaults
- You connect to the peripheral
- Once you get a call to the
didConnectPeripheral
delegate method you can read the count and update your server once you get the value
- The user can now suspend your app and do something else
- Eventually the peripheral will go out of range and you will get a call to
didDisconnectPeripheral
. In this method you immediately re-issue the connect to the peripheral.
- Since you have Core Bluetooth background mode, when the peripheral is eventually seen again you will get another call to
didConnectPeripheral
in the background, and you can proceed as per step 5 (In this case your app is already in the background so it will just go back to suspended state after you have read the data without the user doing anything).
You update the server in step 5. This step executes regardless of whether the app is in the foreground or background. The user doesn't need to open your app.
Now eventually iOS may remove your app from the suspended state, say due to memory pressure. In order to still be able to connect to the peripheral when it is seen you need to opt in to state restoration as described in the Core Bluetooth Programming Guide