Swift中的BLE背景扫描

时间:2015-07-25 22:33:00

标签: ios swift bluetooth-lowenergy

我正在尝试让我的应用程序在后台扫描BLE设备,并在Swift中搜索一些广告数据。我在这里找不到任何有关此内容的教程或问题。

基本上,当应用程序不在前台并且用户重新启动手机时,有没有办法在后台自动执行此操作?: Obtaining Bluetooth LE scan response data with iOS

我希望你能指出我正确的方向。谢谢

1 个答案:

答案 0 :(得分:8)

Step 1: Enable bluetooth background mode for your projects capabilities

enter image description here

Step 2: Make sure the appropriate stuff was added to your 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 have to specify an array of services to scan for. You can't pass it an empty array. It will still scan if you pass nil, just not in the background.

So specify an array of service UUID's like this:

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

Now if you care about options you can pass a dictionary of options in place of the nil I passed above. Mostly, this is used to specify if you want to continuously see a devices RSSI before you connect or if you just want the advertisement packet once. Put a:

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

in the "didDiscoverPeripheral" delegate method to observe the different behavior.

Here is the Dictionary you will pass if you want duplicate keys:

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

Now Apple says that when your app goes in the background mode it defaults this scan option to false but as of iOS 8.3 I have see it keep scanning with duplicate keys.

One final note on background execution. If the iOS decides to suspend your app the scanning stops. I have seen this happen as soon as 30 seconds if there are a bunch of apps running.