To obtain the name of the AirPlay device your iPhone is connected to, you can use the MultipeerConnectivity framework in iOS. This framework allows you to discover and connect to nearby devices, including AirPlay devices, and retrieve their names.
Here's an example of how you can achieve this:
import MultipeerConnectivity
class AirPlayDeviceManager: NSObject, MCNearbyServiceBrowserDelegate {
let serviceType = "airplay"
var browser: MCNearbyServiceBrowser?
var discoveredDevices: [MCPeerID] = []
override init() {
super.init()
browser = MCNearbyServiceBrowser(peer: MCPeerID(displayName: UIDevice.current.name), serviceType: serviceType)
browser?.delegate = self
}
func startBrowsing() {
browser?.startBrowsingForPeers()
}
func stopBrowsing() {
browser?.stopBrowsingForPeers()
}
// MARK: MCNearbyServiceBrowserDelegate
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) {
discoveredDevices.append(peerID)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
if let index = discoveredDevices.firstIndex(of: peerID) {
discoveredDevices.remove(at: index)
}
}
}
// Usage
let airPlayDeviceManager = AirPlayDeviceManager()
airPlayDeviceManager.startBrowsing()
// Wait for some time to allow the browser to discover devices
// You can then access the discovered devices using `airPlayDeviceManager.discoveredDevices`
This code sets up an instance of MCNearbyServiceBrowser with a custom service type of "airplay". It then implements the necessary delegate methods to track discovered and lost AirPlay devices. You can start browsing for devices by calling airPlayDeviceManager.startBrowsing(). After some time, the discovered AirPlay devices will be available in the discoveredDevices array of the AirPlayDeviceManager instance.
Please note that this approach relies on the MultipeerConnectivity framework, which may have limitations or behavior changes in different iOS versions. Make sure to test and adapt the code accordingly.