Reputation: 900
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?
Upvotes: 0
Views: 1593
Reputation: 2237
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
}
}
Upvotes: 0
Reputation: 567
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;
}
}
Upvotes: 1