当我附加到UUID
时,我正在扫描一个在我的Swift应用中工作的IBAction: UIButton
。但是,我现在正试图让它在应用程序启动时立即开始扫描(后台扫描也应该正常工作,因为我将它设置为单个UUID
)。
我已经尝试过我认为合乎逻辑的事情:
self.centralManager?.scanForPeripheralsWithServices(arrayOfServices, options: nil)
viewDidLoad
中的当然arrayOfServices
为UUID
。但这似乎不起作用。
如何让我的应用程序在启动时查找外围设备而不会按下按钮提示?
答案 0 :(得分:1)
您需要初始化CentralManager并等待通过CBCentralManagerDelegate调用centralManagerDidUpdateState。确认状态为PoweredOn后,即可开始扫描。
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;
}
}
答案 1 :(得分:0)
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
}
}