gpt4 book ai didi

ios - CBPeripheral 连接在调用 discoverServices 后保持断开连接

转载 作者:可可西里 更新时间:2023-11-01 05:08:43 24 4
gpt4 key购买 nike

我正在尝试将 coreBluetooth 集成到我的应用程序中。这是我的代码:

@interface Central() <CBCentralManagerDelegate>
@property (strong, nonatomic) CBPeripheral * activePeripheral;
@property (strong, nonatomic) CBCentralManager * centralManager;
@end

@implementation Central

- (id) init
{
self = [super init];
if (self)
{
NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @YES};
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:defaultGlobalQueue options:options];
}
return self;
}

- (void) startScanning:(NSInteger)timeout
{
self.activePeripheral = nil;
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]] options:nil];
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
if (self.activePeripheral != nil)
{
return;
}
self.activePeripheral = peripheral;
[self.centralManager connectPeripheral:peripheral options:nil];

}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
// dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Disconnected from peripheral : %@",peripheral);
if (error)
{
NSLog(@"Error disconnecting peripheral: %@", error.localizedDescription);
//[self didErrorDelegateWithPeripheral:peripheral andError:error andCode:BLE_FAILED_TO_CONNECT];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
//Logic here
}

我在 viewcontroller 中调用 startScanning,它总是进入 (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)错误调用[self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]];

这是我经常看到的错误:

Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us." UserInfo=0x175b8810 {NSLocalizedDescription=The specified device has disconnected from us.}

有人知道我错过了什么吗?

感谢您的帮助。

最佳答案

我终于想通了问题,我们需要在尝试发现服务之前设置发现的外设的委托(delegate)

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
peripheral.delegate = self;
[self.activePeripheral discoverServices:@[[CBUUID UUIDWithString:@"A65eBB2D-3D30-4981-9DB2-1996D88118A0"]]];
}

关于ios - CBPeripheral 连接在调用 discoverServices 后保持断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24614159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com