Search code examples
iosswiftbluetooth-lowenergyscanning

How to scan BLE devices in Background?


I want to scan BLE devices on the background as like a foreground. But my iOS app doesn't work as I expect. Below is my AppDelegate class code.

private var centralManager : CBCentralManager!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)return true
}

func applicationWillEnterForeground(_ application: UIApplication) {

    print("entering foreground...")
}

func applicationDidEnterBackground(_ application: UIApplication) {
    print("entered background...")

    print(centralManager.state)
    centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
}


func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        print("Bluetooth is On")
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    } else {
        print(central.state)
    }
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    print("\nName   : \(peripheral.name ?? "(No name)")")
    print("RSSI   : \(RSSI)")

    let name = peripheral.name ?? ""
    if name.contains("ETGuardian") {

        let DetailData = advertisementData["kCBAdvDataManufacturerData"]
        let DiscoveredData = String(describing: DetailData)

        print(DiscoveredData)

        for ad in advertisementData {
            print("AD Data: \(ad)")
        }
    }

  }
}

Please help me to scan app in background state as like a foreground.


Solution

  • From Docs: link

    Apps that have specified the bluetooth-central background mode are allowed to scan while in the background. That said, they must explicitly scan for one or more services by specifying them in the serviceUUIDs parameter. The CBCentralManager scan option is ignored while scanning in the background.

    For background scanning to work you need to specify serviceUUIDs.