I'm trying to use MultiPeer Connectivity framework with swift ui and am having issues with using ForEach in my view. I have a singleton that I'm using to track connected users in an array:
class MPCManager: NSObject {
static let instance = MPCManager()
var devices: [Device] = []
...
And my device class:
class Device: NSObject {
let peerID: MCPeerID
var session: MCSession?
var name: String
var state = MCSessionState.notConnected
var lastMessageReceived: Message?
...
}
When the MultiPeer connectivity frame finds new peers the MPCManager is appending new devices to the array. I have confirmed this in the debugger. The problem comes when I try to display the devices in a list. Here is the code that I'm using:
struct ContentView : View {
var devices: [Device] = MPCManager.instance.devices
var body: some View {
List {
ForEach(self.devices.identified(by: \.name)) { device in
Text(device.name)
}
}
}
}
When the app starts, the list is displayed but it is empty. When I put a breakpoint in the view code inside the ForEach execution never stops. When I change the array to a hardcoded list of values, it displays just fine. I have also tried referencing the array from the static instance directly in my view like this:
ForEach(self.devices.identified(by: \.name)) { device in
Text(device.name)
}
Still nothing. I'm very new to swift so there may be something easy that I'm missing but I just don't see it. Any ideas?