我有以下设置在后台运行蓝牙扫描,单身:
class BluetoothService: NSObject {
var manager: CBCentralManager!
var characteristic: CBCharacteristic!
var peripheral: CBPeripheral!
let peripheral_name: String = "mygadget"
let service_uuid_array: [CBUUID] = [CBUUID(string: "85948G74-245Z-4861-G54R-198F368E380M")]
static let sharedInstance = BluetoothService()
private override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
}
}
extension BluetoothService: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if (central.state == CBManagerState.poweredOn) {
self.manager?.scanForPeripherals(withServices: service_uuid_array, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if (peripheral.name == self.peripheral_name) {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
self.manager.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
if (central.state == CBManagerState.poweredOn) {
self.manager?.scanForPeripherals(withServices: service_uuid_array, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
}
}
extension BluetoothService: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
}
}
我还激活了背景模式并激活了“使用蓝牙LE配件”
当我使用
时self.manager?.scanForPeripherals(withServices: nil, options: nil)
而不是
self.manager?.scanForPeripherals(withServices: service_uuid_array, options: nil)
它在前景中运行良好,但是当我通过这个数组时我无法正常工作......为什么?
我需要使用“service_uuid_array”才能让它在后台运行..
任何人都可以帮我解决这个问题吗?
谢谢和问候!