当所需蓝牙设备的RSSI强于某个偏移值时,我想使用iOS和CoreBluetooth触发某种HTTP请求。
// Listen to centralManager state
func centralManagerDidUpdateState(central: CBCentralManager) {
switch(central.state){
case CBCentralManagerState.PoweredOff:
stopScanningForPeripherals()
break
case CBCentralManagerState.PoweredOn:
startScanningForPeripherals()
break
case CBCentralManagerState.Resetting:
break
case CBCentralManagerState.Unauthorized:
break
case CBCentralManagerState.Unknown:
break
case CBCentralManagerState.Unsupported:
break
}
}
// Start scanning peripherals
func startScanningForPeripherals(){
print("Start scanning for peripherals \(cbuuid)")
if(cbuuid == nil){
self.centralManager.scanForPeripheralsWithServices(nil, options: nil)
}else{
self.centralManager.scanForPeripheralsWithServices([cbuuid!], options: nil)
}
}
// Callback when received scanning results
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("\(RSSI.intValue) \(peripheral.identifier.UUIDString) != \(appSettings.listeningPeripheralIdentifier?.UUIDString)")
if(!peripheral.identifier.isEqual(appSettings.listeningPeripheralIdentifier)){
return;
}
if(RSSI.intValue == 127 || RSSI.integerValue < appSettings.rssiOffset){
return;
}
httpGateway.postDetectBeacon((appSettings.listeningPeripheralIdentifier?.UUIDString)!, userId: appSettings.userId, callback: { isOk in
print("Sent detect beacon request")
})
}
// Stop scanning
func stopScanningForPeripherals(){
print("Stop scanning for peripherals")
self.centralManager.stopScan()
}
我尝试实现前台任务版本(将其置于UIViewController
内)和后台任务版本(将其置于AppDelegate
内并设置后台挂钩)。结果,在前台任务版本上接收广告包的频率要好得多。但是当应用程序在后台时前台任务版本停止接收,我也希望即使应用程序在后台也能完成工作。
所以我想要的是在
中接收广告包的应用程序都在单个代码库中,并自动切换。可能吗?如果是,我应该在哪里写上面写的代码?