如何在前台和后台运行BLE外设检测?

时间:2015-12-22 18:02:27

标签: ios swift bluetooth-lowenergy cbperipheral ios-bluetooth

当所需蓝牙设备的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内并设置后台挂钩)。结果,在前台任务版本上接收广告包的频率要好得多。但是当应用程序在后台时前台任务版本停止接收,我也希望即使应用程序在后台也能完成工作。

所以我想要的是在

中接收广告包的应用程序
  • 应用程序位于前台时的高频率
  • 应用在后台时的低频率

都在单个代码库中,并自动切换。可能吗?如果是,我应该在哪里写上面写的代码?

0 个答案:

没有答案