How to set peer limit when using NWConnection

When using MultipeerSession I can set a limit to the number of peers on each connection using:

Code Block
func peerDiscovered(_ peer: MCPeerID) -> Bool {
    if multipeerSession.connectedPeers.count > 4 {
        // Do not accept more than four users in the experience.
        return false
    }
}


Im using peer-to-peer with NWConnection, NWListener, and NWBrowser:

Code Block
let params = NWParameters()
params.includePeerToPeer = true


How can I set a limit to the number of users/peers allowed per connection?

Code Block
self.connection?.receiveMessage { (data, context, isComplete, error) in
    if (isComplete) {
        if let data = data, !data.isEmpty {
// do something with data
}
}
}

Answered by Systems Engineer in 651640022
I am not aware of a flag that you can set on NWParameters or on NWListener to control the number of peers. You can control this by hand by managing the amount of client connections you accept in listener.newConnectionHandler.


Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
Accepted Answer
I am not aware of a flag that you can set on NWParameters or on NWListener to control the number of peers. You can control this by hand by managing the amount of client connections you accept in listener.newConnectionHandler.


Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
@meaton Thanks for the help. I had a feeling you was going to say that.

For anyone else who needs to handle this just keep an array of NWConnections and check the count.

Code Block
let yourMaxCount = 10
var connections = [NWConnection]()
listener.newConnectionHandler = { [weak self](newConnection) in
guard let safeSelf = self else { return }
if safeSelf.connections.count >= safeSelf.yourMaxCount { return }
           
// add connection to the array and continue on ...
}

How to set peer limit when using NWConnection
 
 
Q