我想获取我的 iPhone 所连接的 AirPlay 或蓝牙设备的名称。我通过以下代码在某种程度上实现了这一点......
let currentRoute = AVAudioSession.sharedInstance().currentRoute
for output in currentRoute.outputs {
print("Connected port name: \(output.portName)")
}
但是,每当我的 iPhone 连接到 AirPlay 设备(例如 HomePod 或 Apple TV)时,返回的
portName
只是"Speaker"
。我想获取 HomePod 或 Apple TV 的名称。但是,只要我的设备连接到蓝牙,它就可以工作。例如,每当我连接到我的 AirPods 时,都会返回名称"Jacob's AirPods"
。每当我连接到另一个蓝牙设备时,都会返回正确的名称。
我相信获取 AirPlay 设备的名称应该是可能的,因为 Apple 在他们的 Apple Music 应用程序和系统范围内这样做。就像下面...
有什么建议吗?
获取连接的 AirPlay 设备的名称可能有点棘手,因为
AVAudioSession
API 不直接提供此信息。但是,您可以使用 MPVolumeView
类来访问路线按钮及其相关信息。这是您如何实现此目标的示例:
import MediaPlayer
func getConnectedAirPlayDeviceName() -> String? {
let volumeView = MPVolumeView()
var airplayDeviceName: String?
if let routeButton = volumeView.subviews.first(where: { $0 is UIButton }) as? UIButton {
routeButton.sendActions(for: .touchUpInside)
if let alertController = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController as? UIAlertController {
for action in alertController.actions {
if action.style == .default {
airplayDeviceName = action.title
break
}
}
alertController.dismiss(animated: false, completion: nil)
}
}
return airplayDeviceName
}
此函数创建一个
MPVolumeView
实例,找到路线按钮,并模拟一个touchUpInside
事件以显示包含可用路线列表的UIAlertController
。然后它遍历动作以找到默认动作,它代表连接的 AirPlay 设备,并检索其标题。最后,它消除UIAlertController
并返回设备名称。
重要警告: 请注意,此方法依赖于
MPVolumeView
和 UIAlertController
的内部结构,这可能会在未来的 iOS 更新中发生变化。请谨慎使用此方法,因为它可能不是最可靠的解决方案。
要使用此功能,只需在需要连接的AirPlay设备名称时调用它:
if let airplayDeviceName = getConnectedAirPlayDeviceName() {
print("Connected AirPlay device name: \(airplayDeviceName)")
}