了解蓝牙设备已连接情况的最佳方式是什么?我正在使用 CBCentralManager 来识别蓝牙是否已打开,但我无法找到如何识别蓝牙设备是否已连接。
我正在通过连接的蓝牙设备实现 AVAudioSession 呼叫的路由,但 AudioSession 类别更改会被重复调用,因此我无法找到蓝牙设备是否已连接。如果有人尝试实现此行为,您的意见可能会有所帮助。请分享信息。
您在这里描述的蓝牙类型是音频设备,几乎可以肯定是“经典”蓝牙。这与 CoreBluetooth 无关,后者主要通过 BLE(以及其他一些较少使用的协议)处理 GATT 连接。您无法找到有关使用 CoreBluetooth 连接的音频设备的任何信息。
要检查您的音频路由,请参阅 AVAudioSession.currentRoute.outputs。 portType 将告诉您它是否是蓝牙设备。请注意,根据您的目的,有几种类型可以归类为“蓝牙”:
我正在使用
CBPeripheral.state == .connected
检查 BLE 设备的状态。
来自文档:
/**
* @enum CBPeripheralState
*
* @discussion Represents the current connection state of a CBPeripheral.
*
*/
@available(iOS 7.0, *)
public enum CBPeripheralState : Int {
case disconnected = 0
case connecting = 1
case connected = 2
@available(iOS 9.0, *)
case disconnecting = 3
}
使用通知中心
NotificationCenter.default.addObserver(
self,
selector: #selector(handleAudioSessionRouteChange(_:)),
name: NSNotification.Name.AVAudioSessionRouteChange,
object: nil)
@objc private func handleAudioSessionRouteChange(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {return}
switch reason {
case .newDeviceAvailable:
let session = AVAudioSession.sharedInstance()
for output in session.currentRoute.outputs {
print("Bluetooth A2DP device connected: \(output.portName)")
self.speakerButton.setImage(UIImage(systemName: "s.circle.fill"), for: .normal)
}
case .oldDeviceUnavailable:
if let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
for output in previousRoute.outputs{
print("Bluetooth A2DP device disconnected: \(output.portName)")
self.speakerButton.setImage(UIImage(named: "speaker-button"), for: .normal)
}
}
default:
break
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}