1

I need to keep scanning for broadcasts from peripherals while the app is in background and when the phone's screen is off. Scanning from background was successful but I can't scan (can't trigger didDiscoverPeripheral) broadcasts when the phone' screen is off.

So far I've implemented beginBackgroundTaskWithExpirationHandler inside applicationDidEnterBackground and that's how I am able to scan in background. So how should I do this?

Jongers
  • 595
  • 1
  • 9
  • 29
  • 1
    You should specify Bluetooth background mode in your app capabilities. If you do this you don't need to use `beginBackgroundTaskWithExpirationHandler`, but you can't use the duplicates key, you must scan for a specific service UUID and the discovery speed will be slower, particularly when the screen is off – Paulw11 Oct 26 '16 at 02:39
  • That's the weird part, It's already enabled; Uses Bluetooth LE accessories and Acts as a Bluetooth LE accessory. I put a check on all bluetooth related boxes. Also, I specified the specific service UUID that I want to discover. But sadly it doesn't work even in background so I used `beginBackgroundTaskWithExpirationHandler` to make background work. – Jongers Oct 26 '16 at 02:44
  • Are you trying to discover a peripheral you have never seen before or are you trying to connect to a peripheral you have seen before? – Paulw11 Oct 26 '16 at 02:45
  • I'm trying to discover a peripheral I've never seen before. It's like a normal scanning but I have no intention to connect, just read broadcasts. – Jongers Oct 26 '16 at 02:49
  • How long are you waiting for discovery of the peripheral in background mode. It could take up to 60 times longer to discover a peripheral in the background than in the foreground. http://stackoverflow.com/questions/20427230/core-bluetooth-advertise-and-scan-in-the-background – Paulw11 Oct 26 '16 at 02:59

1 Answers1

3

This is not possible. When you tick 'Uses Bluetooth LE accessories' and 'Acts as a Bluetooth LE accessory', when iPhone screen light is turned off, core bluetooth framework stops advertising and scanning. It resumes advertising/scanning once the screen light turns back on. That's the maximum possible achievable scenario in iOS.

If you want to take this further, you can use beginBackgroundTaskWithExpirationHandler - https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiratio but that works hardly for 3 minutes. Those 3 minutes start as soon as the app goes from foreground to background.

For saving battery, iOS seems to automatically turn off the BLE hardware and it goes back on as soon as the device moves/screen wakes up. Because when screen is off, user isn't using the iPhone anyway.

Edit: Unless a device is connected, like a headphone- Though not advertising, existing connected devices can share data.

akashlal.com
  • 356
  • 2
  • 12