Initial send
Code Block let data = NYKeyedArchiver.... let message = NWProtocolWebSocket.Metadata(opcode: .text) let context = NWConnection.ContentContext(identifier: "send", metadata: [message]) connection.send(content: data, contentContext: context, isComplete: true, completion: .contentProcessed({ (error) in if let error = error { return } print("Sent") }))
Receive data and send Echo response
Code Block func receivedIncoming(connection) { connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { (data, context, isComplete, error) in if let err = error { print(err) // never gets hit return } if let data = data, !data.isEmpty { // do something with data if let color = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor { // this should only run on the other device once echo is received after 5 secs self?.view.backgroundColor = color } let randomColor = UIColor.random // func create random color let colorData = randomColor.encode() // func encode color to data DispatchQueue.main.asyncAfter(deadline: .now() + 5) { connection.send(content: colorData, completion : .idempotent) // I've also tried let message = NWProtocolWebSocket.Metadata(opcode: .text) let context = NWConnection.ContentContext(identifier: "send", metadata: [message]) connection.send(content: colorData, contentContext: context, isComplete: true, completion: .contentProcessed({ (error) in if let error = error { return } print("Color data sent") // this always prints })) } } else { print("data is empty") // never gets hit } } }
NWConnection
Code Block weak var delegate: PeerConnectionDelegate? var connection: NWConnection? // Outgoing Connection init(endPoint: NWEndpoint, delegate: PeerConnectionDelegate) { self.delegate = delegate let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 let parameters = NWParameters(tls: nil, tcp: tcpOptions) parameters.includePeerToPeer = true parameters.allowLocalEndpointReuse = true connection = NWConnection(to: endPoint, using: parameters) startOutgoingConnection() } // Incoming Connection init(connection: NWConnection, delegate: PeerConnectionDelegate) { self.delegate = delegate self.connection = connection startIncomingConnection() } func startIncomingConnection() { connection?.stateUpdateHandler = { (nwConnectionState) in case .ready: self.delegate?.receivedIncoming(connection) // ... }
Why is the echo data being sent but not received?