Member-only story
More Naked Networking, more SwiftUI
If you came here from Naked Networking with SwiftUI, you’re in the right place. If you haven’t, you need to read this first.
Let's plough ahead if you already read its sister article and created the nakedNetwoking project.
We will be implementing the talking part of our super simple app. It is I fear a little bit chicken and egg but bare with me. I think I’ll go the same way as the previous code. I’ll start with the network and finish with SwiftUI.
Network
Let's return to our connect class and define the talker with this code.
func connectToUDP(hostUDP:NWEndpoint.Host,portUDP:NWEndpoint.Port) {
self.talking = NWConnection(host: hostUDP, port: portUDP, using: .udp)
self.talking?.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
break
default:
break
}
}
self.talking?.start(queue: .main)
}
We start by defining the initial connection. As with the other article, you have more cases to add here, but I’m focusing on naked coding.
Having made the connection, we can use this method to send some data.
func sendUDP(_ content: String) {
let contentToSendUDP = content.data(using: String.Encoding.utf8)
self.talking?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
// code
} else {
print("ERROR! Error when data (Type: String)…