Multipeer Connectivity框架数据发送失败:[GCKSession] 未处于连接状态问题求助
Let’s break down why you’re seeing those "not connected" errors and fix the data sending issue:
1. Don’t Trust connectedPeers Alone — Check Real-Time Peer State
The connectedPeers array can be out of sync with the actual connection state of peers (it might show a peer as connected before the handshake fully completes). Instead, always verify a peer’s state using mcSession.state(for: peer) before sending data.
Modify your send method to filter for truly connected peers:
func sendPayData(totalUser: String) { // Filter peers that are actually in .connected state let trulyConnectedPeers = mcSession.connectedPeers.filter { mcSession.state(for: $0) == .connected } guard !trulyConnectedPeers.isEmpty else { print("No peers are fully connected yet") return } guard let data = totalUser.data(using: .ascii) else { print("Failed to convert string to ASCII data") return } do { try mcSession.send(data, toPeers: trulyConnectedPeers, with: .reliable) } catch let error as NSError { // Log detailed error info for debugging print("Send Error: Domain=\(error.domain), Code=\(error.code), Message=\(error.localizedDescription)") let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }
2. Ensure You’re Reacting to Connection State Changes
Make sure your MCSessionDelegate properly tracks peer states, and only send data after a peer transitions to .connected:
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { DispatchQueue.main.async { switch state { case .connected: print("✅ Peer \(peerID.displayName) is fully connected and ready for data") // Trigger data sending here if needed, or update a local list of ready peers case .connecting: print("🔄 Peer \(peerID.displayName) is connecting...") case .notConnected: print("❌ Peer \(peerID.displayName) disconnected") @unknown default: print("❓ Unknown state for peer \(peerID.displayName)") } } }
3. Validate Your MCSession Initialization
Double-check how you’re initializing your MCSession — even with encryptionPreference set to .none, misconfigured security settings can break connections:
// Correct initialization for unencrypted sessions let myPeerID = MCPeerID(displayName: UIDevice.current.name) let mcSession = MCSession(peer: myPeerID, securityIdentity: nil, encryptionPreference: .none) mcSession.delegate = self
If you’re passing a securityIdentity value by accident, it can cause silent connection failures even if peers appear in connectedPeers.
4. Verify MCBrowserViewController Integration
Ensure your browser delegate is correctly handling new connections and using the same MCSession instance:
func browser(_ browser: MCBrowserViewController, didConnectPeer peerID: MCPeerID, toSession session: MCSession) { dismiss(animated: true) print("Browser connected to \(peerID.displayName)") // Do NOT create a new MCSession here — use your existing mcSession instance }
5. Debug with Detailed Logs
Add logs to confirm the state of peers right before sending:
for peer in mcSession.connectedPeers { print("Peer: \(peer.displayName) | State: \(mcSession.state(for: peer))") }
This will tell you if connectedPeers includes peers that are still in .connecting state, which is the most likely cause of your error.
内容的提问来源于stack exchange,提问作者JS__2008

