I am trying to send an image via an UDP connection.
class Connect: NSObject {
var connection: NWConnection?
func connectToUDP(host: String, port: UInt16) {
let host = NWEndpoint.Host(host)
guard let port = NWEndpoint.Port(rawValue: port) else { return }
let messageToUDP = "Bonjour"
connection = NWConnection(host: host, port: port, using: .udp)
connection?.stateUpdateHandler = { (newState) in
print("This is stateUpdateHandler:")
switch (newState) {
case .ready:
print("State: Ready\n")
self.sendUDP(messageToUDP)
self.receiveUDP()
default:
print("ERROR! State not defined!\n")
}
}
connection?.start(queue: .global())
}
func sendUDP(_ content: Data) {
connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
print("Data was sent to UDP")
} else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
}
})))
}
}
I converted the image into data and when I send it :
guard let image = UIGraphicsGetImageFromCurrentImageContext(),
let data = image.pngData() else { return }
connect.connectToUDP(host: "192.168.XX.XX", port: 10000)
connect.sendUDP(data)
I got this error
ERROR! Error when data (Type: Data) sending. NWError: POSIXErrorCode: Message too long
How can I split the data in packets and in order the data get fully reconstructed by the receiver ?