简体   繁体   中英

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?

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;
    }
}

Swift 3

func centralManagerDidUpdateState(_ central: CBCentralManager){

    switch central.state{

    case .poweredOn:
        print("Power On")
        central.scanForPeripherals(withServices: nil, options: nil)     
        break

    case .poweredOff:
        print("Power Off")

        break

    case .unsupported:
        print("Power Unsupported")
        break

    case .resetting:
        print("Power Resetting")
        break

    case .unauthorized:
        print("Power Unauthorized")
        break

    case .unknown:
        print("Power Unknown")
        break
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM