I am trying to receive UDP datagrams . I am lost with the connection.receiveMessage(completion:) not being executed. I've used the example above with minor changes:
var connection: NWConnection
var address: NWEndpoint.Host
var port: NWEndpoint.Port
var resultHandler = NWConnection.SendCompletion.contentProcessed { NWError in
guard NWError == nil else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
return
}
}
init?(address newAddress: String, port newPort: Int32) {
let codedAddress = NWEndpoint.Host( newAddress )
let codedPort = NWEndpoint.Port(rawValue: NWEndpoint.Port.RawValue(newPort))
guard codedPort != nil else {
print("Failed to create connection port", codedPort as Any)
return nil
}
address = codedAddress
port = codedPort!
connection = NWConnection(host: address, port: port, using: .udp)
connection.stateUpdateHandler = { newState in
switch (newState) {
case .ready:
print("State: Ready")
self.receive()
case .setup:
print("State: Setup")
case .cancelled:
print("State: Cancelled")
case .preparing:
print("State: Preparing")
default:
print("ERROR! State not defined!\n")
}
}
connection.start(queue: .global())
}
deinit {
connection.cancel()
}
//func sendAndReceive(_ data: Data) {
func receive() {
print("receive starts...")
//self.connection.send(content: data, completion: self.resultHandler)
self.connection.receiveMessage { data, context, isComplete, error in
print("...Receive isComplete: " + isComplete.description)
guard let data = data else {
print("...Error: Received nil Data")
return
}
print("...I am not falling through")
print(String(data: data, encoding: .utf8) as Any)
}
print("...or am I?")
}
}
The print outputs show the init proceeds to ready, but the receiveMessage completion: does not get executed, as the print("...I am not falling through") does not appear...
State: Preparing
State: Ready
receive starts...
...or am I?
Any idea what goes wrong?