无法写入或读取CBPeripheral | CBMutableCharacteristic

时间:2016-03-14 20:09:56

标签: ios swift bluetooth

我想要连接到蓝牙硬件,但是我无法收到通知,当值更新时,读取阅读,这是我的代码:

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {

    guard peripheral == self.peripheral && error == nil else {
        return
    }

    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            if characteristic.UUID == QuadrarCharacteristicUUID {
                if let peripheral = self.peripheral {
                    self.quadrarCharacteristic = CBMutableCharacteristic(type: QuadrarCharacteristicUUID,
                        properties: [.Read, .Write, .Notify],
                        value: nil,
                        permissions: [.Readable, .Writeable])
                    self.quadrarCharacteristic?.descriptors = characteristic.descriptors
                    peripheral.setNotifyValue(true, forCharacteristic: self.quadrarCharacteristic!)
                }
            }
        }
    }
}

当我写作时:

 func writeBytes() {
           self.quadrarCharacteristic!.service.peripheral.writeValue(self.bytesToWriteArray[self.senderCounter], 
            forCharacteristic: self.quadrarCharacteristic!, type: CBCharacteristicWriteType.WithResponse)
    }

我知道,即使写作也没有用,因为

 func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?)

未被调用... 但如果我只使用

var quadrarCharacteristic: CBCharacteristic?

并尝试编写它,作为非CBMutableCharacteristic,它可以工作,但我不能让通知工作...

1 个答案:

答案 0 :(得分:2)

当您作为中心时,您不会创建新的CBMutableCharacteristic,只需使用CBCharacteristic中提供给您的didDiscoverCharacteristicsForService个对象 -

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {

    guard peripheral == self.peripheral && error == nil else {
        return
    }

    if let characteristics = service.characteristics {
        for characteristic in characteristics {
            if characteristic.UUID == QuadrarCharacteristicUUID {
                self.quadrarCharacteristic=charateristic
                peripheral.setNotifyValue(true, forCharacteristic: self.quadrarCharacteristic!)
                }
            }
        }
    }
}

此外,您需要确认您的特性支持通知。