我正在为Objective-C开发BLE。

我用以下代码定义UUID:

    static NSString *const LEDStateCharacteristicUUID = @"ffffffff-7777-7uj7-a111-d631d00173f4";

我想通过以下代码将特征写入BLE设备,它需要传递3个参数:1.数据2.特性3.类型
CBCharacteristic *chara = ??? // how to set the characteristic via above UUID let it can pass to following function?

[peripheral writeValue:data forCharacteristic:chara type:CBCharacteristicWriteWithoutResponse];

如何通过上面的UUID设置特性使其可以传递给writeCharacteristic函数?

提前致谢。

最佳答案

首先,您需要知道所需的服务UUID和所需的特征UUID。当拥有这些UUID时,可以使用以下逻辑来获取正确的特征实例:

- (CBCharacteristic *)characteristicWithUUID:(CBUUID *)characteristicUUID forServiceUUID:(CBUUID *)serviceUUID inPeripheral:(CBPeripheral *)peripheral {

    CBCharacteristic *returnCharacteristic  = nil;
    for (CBService *service in peripheral.services) {

       if ([service.UUID isEqual:serviceUUID]) {
           for (CBCharacteristic *characteristic in service.characteristics) {

                if ([characteristic.UUID isEqual:characteristicUUID]) {

                    returnCharacteristic = characteristic;
                }
            }
        }
    }
    return returnCharacteristic;
}

10-08 05:26