我将Mac设置为使用CoreBluetooth作为CBPeripheralManager的蓝牙附件。 Mac在设定的特征CBUUID上做广告,一旦有订阅者,我单击一个按钮,每半秒传输一次UTF-8编码的时间戳。

我已将iPhone设置为CBCentralManager并订阅了适当的功能。每当iPhone收到数据并且应用程序处于活动状态时,我都会使用解码后的时间戳更新iPhone的UI。 bluetooth-central背景模式在.plist文件中设置。

iPhone继续调试打印并更新时间戳的UI约25秒,然后停止。无论应用是在前台还是在后台,都会发生这种情况。编辑:CBPeripheralManager此时收到一个didUnsubscribeFrom characteristic回调。我没有看到didUnsubscribeFrom被调用的任何原因,也不知道为什么它总是在25秒后出现。

CBPeripheralManager继续愉快地发送其时间戳。 CBPeripheralManagerupdateData(_:for:onSubscribedCentrals:)调用的返回值始终为true,表示队列永远不会满。

这里涉及很多代码,显示了最相关的代码。

CBCentralManager应用中:

 func centralManagerDidUpdateState(_ central: CBCentralManager) {
     print(central.state.rawValue)
     centralManager.scanForPeripherals(withServices: [timeUUID], options: nil)
     print("scanning")
 }

 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
     peripheral.delegate = self
     peripheral.discoverServices(nil)

     print("connected")
 }

 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
     print(peripheral.name as Any)
     print(advertisementData[CBAdvertisementDataServiceUUIDsKey] as! Array<CBUUID>)
     self.peripheralController = peripheral

     self.centralManager.connect(peripheral, options: nil)
 }

 func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    if service.uuid.uuidString == timeUUID.uuidString {
        peripheralController.setNotifyValue(true, for: service.characteristics!.first!)
        peripheralController.readValue(for: service.characteristics!.first!) // EDIT: This was the offending line
    }
 }

 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

    if characteristic.uuid.uuidString == timeUUID.uuidString {
        if let valueFrom = characteristic.value  {
            if let this = String(data: valueFrom, encoding: .utf8) {
                if UIApplication.shared.applicationState == .active {
                    label.text = this
                    print("ACTIVE \(this)")
                } else if UIApplication.shared.applicationState == .background {
                    print("BACKGROUND \(this)")
                } else if UIApplication.shared.applicationState == .inactive {
                    print("INACTIVE \(this)")
                }
            }
        }
    }
 }


CBPeripheralManager应用中:

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    myCharacteristic = CBMutableCharacteristic(type: myServiceUUID, properties: [CBCharacteristicProperties.read, CBCharacteristicProperties.notify], value: nil, permissions: CBAttributePermissions.readable)
    let myService = CBMutableService(type: myServiceUUID, primary: true)
    myService.characteristics = [myCharacteristic]
    bluetoothController.add(myService)
}

func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
    print(characteristic.uuid)
    subscriber = central
}

func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
    print(characteristic)
    print("unsubscribe")
}

func repeatAdvertisement() {
    timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [unowned self] (timerRef) in
        guard let maybeTimer = self.timer, maybeTimer.isValid else { return }
        let datum = Date()
        let stringFromDate = self.dateFormatter.string(from: datum)
        let data = stringFromDate.data(using: .utf8)
        print(data!.count)
        //        myCharacteristic.value = data
        let myService = CBMutableService(type: self.myServiceUUID, primary: true)
        myService.characteristics = [self.myCharacteristic]
        let did = self.bluetoothController.updateValue(data!, for: self.myCharacteristic as! CBMutableCharacteristic, onSubscribedCentrals: [self.subscriber])
        print("timed \(stringFromDate) \(did)")
    }


}


func advertise() {
    if timer == nil {
        repeatAdvertisement()
    } else {
        timer?.invalidate()
        timer = nil
    }
}


让我知道您还需要什么。

最佳答案

好,看在天堂的份上问题是我根据一些示例代码在应用程序中使用了该行peripheralController.readValue(for: service.characteristics!.first!),这是不必要的。

显然,对readValue(for:)的调用导致某种超时。我在应用程序外编辑了该行,并愉快地不断更新。

如果有一天有人面对同样的事情,则不提问题,并添加此答案。

关于ios - iOS BluetoothLE:CBCentralManager取消订阅更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44340463/

10-10 23:25