iOS 中如何知道蓝牙设备是否已连接?

问题描述 投票:0回答:3

了解蓝牙设备已连接情况的最佳方式是什么?我正在使用 CBCentralManager 来识别蓝牙是否已打开,但我无法找到如何识别蓝牙设备是否已连接。

我正在通过连接的蓝牙设备实现 AVAudioSession 呼叫的路由,但 AudioSession 类别更改会被重复调用,因此我无法找到蓝牙设备是否已连接。如果有人尝试实现此行为,您的意见可能会有所帮助。请分享信息。

ios core-bluetooth ios-bluetooth cbcentralmanager
3个回答
1
投票

您在这里描述的蓝牙类型是音频设备,几乎可以肯定是“经典”蓝牙。这与 CoreBluetooth 无关,后者主要通过 BLE(以及其他一些较少使用的协议)处理 GATT 连接。您无法找到有关使用 CoreBluetooth 连接的音频设备的任何信息。

要检查您的音频路由,请参阅 AVAudioSession.currentRoute.outputs。 portType 将告诉您它是否是蓝牙设备。请注意,根据您的目的,有几种类型可以归类为“蓝牙”:

  • bluetoothA2DP:高品质音乐(单向)
  • bluetoothHFP:双向(麦克风/扬声器)语音;低质量
  • carAudio:CarPlay(非 CarPlay 系统是 A2DP 或 HFP)
  • 蓝牙LE:助听器。虽然这是 BLE,但它不是 CoreBluetooth 的一部分。

0
投票

我正在使用

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
}

0
投票

使用通知中心

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)
        }
© www.soinside.com 2019 - 2024. All rights reserved.