我正在使用带有警报通知服务的 iOS 6 Corebluetooth。
尽管委托方法中的广告数据看起来是正确的,但由于某种原因,服务没有出现在外围设备中。
这是委托方法:
(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
bool ourGuy = NO;
NSLog(@"DATA: %@", advertisementData);
NSArray *keys = [advertisementData allKeys];
for (int i = 0; i < [keys count]; ++i) {
id key = [keys objectAtIndex: i];
NSString *keyName = (NSString *) key;
NSObject *value = [advertisementData objectForKey: key];
if ([value isKindOfClass: [NSArray class]]) {
printf(" key: %s\n", [keyName cStringUsingEncoding: NSUTF8StringEncoding]);
if ([keyName isEqualToString: @"kCBAdvDataServiceUUIDs"] ){
NSArray *values = (NSArray *) value;
for (int j = 0; j < [values count]; ++j) {
if ([[values objectAtIndex: j] isKindOfClass: [CBUUID class]]) {
CBUUID *uuid = [values objectAtIndex: j];
NSString *uuidString = [uuid representativeString];
NSLog(@"FOUND SERVICE UUID %@", uuidString);
if ([uuidString isEqualToString:kalertNotificationServiceUUIDString]){
NSLog(@"Connecting");
if (![foundPeripherals containsObject:peripheral]) {
ourGuy = YES;
}
}
} else {
const char *valueString = [[value description] cStringUsingEncoding: NSUTF8StringEncoding];
printf(" value(%d): %s\n", j, valueString);
}
}
}
} else {
const char *valueString = [[value description] cStringUsingEncoding: NSUTF8StringEncoding];
printf(" key: %s, value: %s\n", [keyName cStringUsingEncoding: NSUTF8StringEncoding], valueString);
}
}
if (ourGuy){
[foundPeripherals addObject:peripheral];
peripheral.delegate = self;
[centralManager connectPeripheral:peripheral options:nil];
}
}
日志如下所示:
2013-08-25 23:30:17.417 myControl[688:907] DATA: {
kCBAdvDataLocalName = myTEST;
kCBAdvDataServiceUUIDs = (
"Unknown (<1811>)",
"Unknown (<180f>)"
);
}
key: kCBAdvDataServiceUUIDs
2013-08-25 23:30:17.419 myControl[688:907] FOUND SERVICE UUID 1811
2013-08-25 23:30:17.421 myControl[688:907] Connecting
2013-08-25 23:30:17.422 myControl[688:907] FOUND SERVICE UUID 180f
key: kCBAdvDataLocalName, value: myTEST
key: kCBAdvDataTxPowerLevel, value: -8
服务发现的委托方法:
- (void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
for (int i=0; i < peripheral.services.count; i++) {
CBService *s = [peripheral.services objectAtIndex:i];
NSLog(@" UUUID %@", [s.UUID representativeString]);
// [peripheral discoverCharacteristics:nil forService:s];
}
}
该方法的日志:
2013-08-25 23:30:18.266 myControl[688:907] UUUID 1800
2013-08-25 23:30:18.269 myControl[688:907] UUUID 1801
这是 BLE GATT 和 GAP 的两个 UUID。在广告数据中看到的外围设备服务永远不会出现。我究竟做错了什么?