mm2*_*m24 0 ios core-bluetooth cbperipheral cbperipheralmanager
我写了一些CoreBluetooth代码,我可以发现设备,但我似乎无法发现特征无法发现我发现的外围设备的有人有一个好的示例代码可以用来验证我的代码吗?
\n\n这是我写的:
\n\n#import "ViewController.h"\n@property(nonatomic, strong) CBCentralManager* centralmanager;\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n self.centralmanager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];\n}\n\n- (void)centralManagerDidUpdateState:(CBCentralManager *)central\n{\n CBCentralManagerState currentState = central.state;\n NSLog(@"state %i", currentState);\n\n switch (central.state)\n {\n case CBCentralManagerStatePoweredOn:\n {\n NSDictionary *options = @{\n CBCentralManagerScanOptionAllowDuplicatesKey: @YES\n };\n [self.centralmanager scanForPeripheralsWithServices:nil options:options];\n NSLog(@"I just started scanning for peripherals");\n break;\n }\n }\n}\n- (void)centralManager:(CBCentralManager *)central\n didConnectPeripheral:(CBPeripheral *)peripheral{\n NSLog(@"connected!");\n}\n\n- (void) centralManager:(CBCentralManager *)central\n didDiscoverPeripheral:(CBPeripheral *)peripheral\n advertisementData:(NSDictionary *)advertisementData\n RSSI:(NSNumber *)RSSI\n{\n [self.centralmanager connectPeripheral:peripheral options:nil];\n\n if ([[advertisementData description] containsString:@\xe2\x80\x9ckeyword\xe2\x80\x9d]) {\n\n\n NSLog(@"peripheral count %lu", (unsigned long)[peripheral.services count]);\n [peripheral.services count];\n for (int i=0; [peripheral.services count]; i++) {\n for (CBService *s in peripheral.services) {\n [peripheral discoverCharacteristics:nil forService:s];\n }\n }\n }\n}\n\n\n- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{\n NSLog(@"did discover characteristic for service");\n}\n\n- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSArray *)serviceUuids{\n NSLog(@"discovered a peripheral\'s services: %@", serviceUuids);\n}\nRun Code Online (Sandbox Code Playgroud)\n
看这里: 示例代码
基本上这个过程是:
随后,您无需搜索和发现设备,因为可以从缓存中检索先前发现的设备并直接连接。
编辑: - - - - - - - - - -
阅读示例:
[aPeripheral readValueForCharacteristic:aChar];
通知示例:
[aPeripheral setNotifyValue:YES forCharacteristic:aChar];
- (void) peripheral:(CBPeripheral *)aPeripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error当 BLE 设备返回值时,这两个调用都会导致调用 - 函数。使用通知时,每次设备更新该特征的值时,都会自动调用此回调。