我已经看到了这种性质的一些问题,但似乎没有一个问题可以解决我的情况。我试图连接到BLE设备。一切顺利,直到我进入回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
似乎从未调用过。这就是我所拥有的:
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
self.connected = [NSString stringWithFormat:@"Connected: %@", peripheral.state == CBPeripheralStateConnected ? @"YES" : @"NO"];
NSLog(@"%@", self.connected);
[peripheral setDelegate:self];
if (peripheral.services) {
[self peripheral:peripheral didDiscoverServices:nil]; //already discovered services, DO NOT re-discover. Just pass along the peripheral.
} else {
[peripheral discoverServices:nil]; //yet to discover, normal path. Discover your services needed
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
NSLog(@"here");
for(CBService* svc in peripheral.services)
{
if(svc.characteristics)
[self peripheral:peripheral didDiscoverCharacteristicsForService:svc error:nil]; //already discovered characteristic before, DO NOT do it again
else
[peripheral discoverCharacteristics:nil
forService:svc]; //need to discover characteristics
NSString *string = [NSString stringWithFormat:@"Discovered service: %@", svc.UUID];
NSLog(@"%@", string);
[self appendTextToDeviceInfo:string];
}
}
我可以看到日志输出:
已连接:是
但就是这样。似乎没有调用didDiscoverServices回调中的任何内容。我已删除并重新安装了该应用,并重新启动了该设备。
任何人都能看到我做错了什么?谢谢!
修改
这是头文件:
#import <UIKit/UIKit.h>
@import CoreBluetooth;
@import QuartzCore;
@interface ViewController : UIViewController <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *myPeripheral;
@end
编辑#2
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI
{
NSString *localName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
if ([localName length] > 0) {
NSLog(@"Found the device: %@", localName);
[_centralManager cancelPeripheralConnection:peripheral]; //IMPORTANT, to clear off any pending connections
[_centralManager stopScan];
_myPeripheral = peripheral;
_myPeripheral.delegate = self;
[_centralManager connectPeripheral:_myPeripheral options:nil];
}
}