在 iOS 中检测 CBPeripheral 对象状态从 "Connected" 到 "Disconnected" 的变化

Detecting CBPeripheral object state change from "Connected" to "Disconnected" in iOS

在iOS.

中检测CBPeripheral对象状态从"Connected"到"Disconnected"有什么原因吗?

要检测 Core Bluetooth Peripheral 对象是否断开连接,请使用 centralManager(_:didDisconnectPeripheral:error:) 实例方法,该方法告诉委托人中央管理器与外围设备断开连接:

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

         print(peripheral.state)    // CBPeripheralState
     }

不要忘记设置一个 delegate 实例 属性,它是指定的委托对象,用于从 CBPeripheralDelegate 协议接收外围事件,该协议提供外围服务使用的更新:

weak var delegate: CBPeripheralDelegate? { get set }

CBPeripheralState有三种情况:

enum CBPeripheralState : Int {

    case disconnected = 0
    case connecting = 1
    case connected = 2
}