0

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.

chirag90
  • 2,211
  • 1
  • 22
  • 37
Vikas
  • 1,548
  • 2
  • 12
  • 25
  • Possible duplicate of [Background Scanning for BLE in Swift](https://stackoverflow.com/questions/31631772/background-scanning-for-ble-in-swift) – chirag90 Sep 12 '19 at 10:22
  • I tried this solution, but not solved my problem. – Vikas Sep 12 '19 at 10:26

1 Answers1

4

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.

Shreeram Bhat
  • 2,849
  • 2
  • 11
  • 19