Background scanning for BLE in Swift

I am trying to test a BLE device app in the background and search ad data for some information about ads in Swift. I haven't been able to find any tutorials or questions here that cover this.

Basically, is there a way to do this automatically in the background when the app is not in the foreground and when the user restarted their phone ?: Receiving Bluetooth LE scan response data from iOS

Hope you can point me in the right direction. Thanks you

+3


source to share


1 answer


Step 1: enable Bluetooth background for your projects

enter image description here

Step 2. Make sure you add the appropriate material to the info.plist file.

enter image description here

Here is the plist code if it didn't add it:

<key>UIBackgroundModes</key>
 <array>
  <string>audio</string>
  <string>bluetooth-central</string>
 </array>

      

Then when you call "scanForPeripheralsWithServices" on your CBCentralmanager, you need to specify an array of services to scan. You cannot pass an empty array to it. It will scan anyway if you pass null and not in the background.

So, specify an array of the UUID of the service like this:



let arrayOfServices: [CBUUID] = [CBUUID(string: "8888")]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)

      

Now if you like the parameters, you can pass the options dictionary instead of the nil I went through above. Basically, this is used to indicate if you want to see the RSSI of devices all the time before connecting, or if you just want the ad package to be displayed once. Place a:

println(advertisementData["kCBAdvDataLocalName"] as! String) 
println(advertisementData["kCBAdvDataManufacturerData"] as! NSData)

      

in the did.DiscoverPeripheral delegate method to observe other behavior.

Here is the dictionary you pass in if you want to duplicate keys:

let dictionaryOfOptions = [CBCentralManagerScanOptionAllowDuplicatesKey : true]
self.myBluetoothManager?.scanForPeripheralsWithServices(arrayOfServices, options: dictionaryOfOptions)

      

Now Apple says that when your app goes into the background this scan option is set to false by default, but as of iOS 8.3 I can see it keep scanning with duplicate keys.

One final note on background execution. If iOS decides to pause your app, scanning will stop. I have seen this as soon as 30 seconds if there are many applications running.

+7


source







All Articles