iOS CBPeripheral 连接问题

Posted

技术标签:

【中文标题】iOS CBPeripheral 连接问题【英文标题】:iOS CBPeripheral connect Questions 【发布时间】:2015-12-16 10:57:06 【问题描述】:

我调用方法

(void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;

连接我的设备,我的设备在范围内,但我的应用程序仍然无法连接我的设备成功,当我关闭系统BT然后打开BT时,我的应用程序将连接我的设备成功,我没有知道为什么吗?

如果我不关闭BT再打开,我可以调用第一个调用方法

(void)cancelPeripheralConnection:(CBPeripheral *)peripheral;

然后调用

(void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;

这有意义吗?

【问题讨论】:

更好的调用:-connectPeripheral:options:-cancelPeripheralConnection: 【参考方案1】:

要检查天气您的设备是否已连接,您可以使用以下两种委托方法: 目标 C:

1) -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

2) -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

@property (nonatomic, strong) CBPeripheral *heartRatePeripheral;
#define heartRateServiceCBUUID [CBUUID UUIDWithString:@"0x180D"]

-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral 
  *)peripheral
 
  [self.Customdelegate HRMoniterStatus:peripheral Status:@"Connected"];
  [_heartRatePeripheral discoverServices:@[heartRateServiceCBUUID]];

自定义委托:

-(void)HRMoniterStatus:(CBPeripheral *)HRMoniter Status:(NSString 
*)connectionStatus

  NSLog(@"HRMoniter connection status ::- %@",connectionStatus);


斯威夫特:

1) func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)

2) func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)

let heartRateServiceCBUUID = CBUUID(string: "0x180D")

let heartRatePeripheral : CBPeripheral

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)

    Customdelegate.hrMoniterStatus(peripheral, status: "Connected")
    heartRatePeripheral.discoverServices([heartRateServiceCBUUID])

自定义委托:

func hrMoniterStatus(_ HRMoniter: CBPeripheral?, status connectionStatus: String?) 

   print("HRMoniter connection status ::- \(connectionStatus ?? "")")

【讨论】:

以上是关于iOS CBPeripheral 连接问题的主要内容,如果未能解决你的问题,请参考以下文章

在连接之前识别 CBPeripheral 的类型

iOS 11 CoreBluetooth:无法删除关键路径“委托”的观察者 CBPeripheral

如何自动连接 CBPeripheral(带有 iBeacon + 蓝牙芯片的 BLE 设备)并且应用程序未运行

如何知道 CBPeripheral 何时不再可用

如何在 ios swift 中连接蓝牙低功耗?

为啥 CBPeripheral 标识符和 UUID 不同?