Search code examples
iosswiftbluetooth-lowenergycore-bluetooth

BLE Scanning at Start in Swift


I have scanning for a single UUID working in my Swift app when attached to an IBAction: UIButton. However, I'm now trying to get it to start scanning right when the app starts (background scanning should also be working as I have it set to a single UUID).

I've tried what I think is logical:

self.centralManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)

in viewDidLoad with arrayOfServices being the UUID of course. But this doesn't seem to work.

How do I get my app to look for peripherals upon start up without being prompted with a button press?


Solution

  • You will need to initialize the CentralManager and wait for the centralManagerDidUpdateState call via the CBCentralManagerDelegate. Once you verify that the State is PoweredOn, you can start scanning.

    func centralManagerDidUpdateState(central: CBCentralManager) {
    
        switch central.state
        {
        case CBCentralManagerState.PoweredOff:
            print("Powered Off")
        case CBCentralManagerState.PoweredOn:
            print("Powered On")
            //Start Scanning Here
             self.centralManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)
        case CBCentralManagerState.Unsupported,
             CBCentralManagerState.Resetting,
             CBCentralManagerState.Unauthorized,
             CBCentralManagerState.Unknown:
            print("Unexpected CBCentralManager State")
            fallthrough
        default:
            break;
        }
    }