Search code examples
iosswiftbluetooth-lowenergycore-bluetooth

Background scan BLE in swift


I am trying to connect with BLE in background but it did not connect in background. It is working when my app is in foreground. I am trying to scan with UUID of the peripheral. Here is the attached code.

 override func viewDidLoad() {
        super.viewDidLoad()

        manager = CBCentralManager(delegate: self, queue: nil)

    }


    func centralManagerDidUpdateState(_ central: CBCentralManager) {

        var msg = ""

        switch central.state {

            case .poweredOff:
                msg = "Bluetooth is Off"
            case .poweredOn:
                msg = "Bluetooth is On"
                let arrayOfServices: [CBUUID] = [CBUUID(string: "CCAExxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")]

                manager?.scanForPeripherals(withServices:arrayOfServices, options: nil)
            case .unsupported:
                msg = "Not Supported"
            default:
                msg = "Not Connected"

        }

        print("STATE: " + msg)

    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        print("Name: \(peripheral.name)") //print the names of all peripherals connected.

        //you are going to use the name here down here ⇩

        if peripheral.name == "Name of device" { //if is it my peripheral, then connect

            self.myBluetoothPeripheral = peripheral     //save peripheral
            self.myBluetoothPeripheral.delegate = self

            manager.stopScan()                          //stop scanning for peripherals
            manager.connect(myBluetoothPeripheral, options: nil) //connect to my peripheral

        }
    }

How can resolve it?


Solution

  • Turn on 'Background Modes' Capabilities.

    And turn on below two option: 1. User Bluetooth LE accessories. 2. Act as Bluetooth LE accessory.

    Do same as Screenshot:

    enter image description here

    Now BLE is working in background mode in iOS application.