Skip to content

Instantly share code, notes, and snippets.

@twissmueller
Last active December 28, 2020 15:07
Show Gist options
  • Save twissmueller/33247fdd9ca0bd68459a953e8e1dfe8e to your computer and use it in GitHub Desktop.
Save twissmueller/33247fdd9ca0bd68459a953e8e1dfe8e to your computer and use it in GitHub Desktop.
A template for sending and receiving data on a UDP connection
import SwiftUI
import Network
struct ContentView: View {
@State var connection: NWConnection?
var host: NWEndpoint.Host = "127.0.0.1"
var port: NWEndpoint.Port = 1234
var body: some View {
VStack {
Spacer()
Button("Connect") {
NSLog("Connect pressed")
connect()
}
Spacer()
Button("Send") {
NSLog("Send pressed")
send("hello".data(using: .utf8)!)
}
Spacer()
}.padding()
}
func send(_ payload: Data) {
connection!.send(content: payload, completion: .contentProcessed({ sendError in
if let error = sendError {
NSLog("Unable to process and send the data: \(error)")
} else {
NSLog("Data has been sent")
connection!.receiveMessage { (data, context, isComplete, error) in
guard let myData = data else { return }
NSLog("Received message: " + String(decoding: myData, as: UTF8.self))
}
}
}))
}
func connect() {
connection = NWConnection(host: host, port: port, using: .udp)
connection!.stateUpdateHandler = { (newState) in
switch (newState) {
case .preparing:
NSLog("Entered state: preparing")
case .ready:
NSLog("Entered state: ready")
case .setup:
NSLog("Entered state: setup")
case .cancelled:
NSLog("Entered state: cancelled")
case .waiting:
NSLog("Entered state: waiting")
case .failed:
NSLog("Entered state: failed")
default:
NSLog("Entered an unknown state")
}
}
connection!.viabilityUpdateHandler = { (isViable) in
if (isViable) {
NSLog("Connection is viable")
} else {
NSLog("Connection is not viable")
}
}
connection!.betterPathUpdateHandler = { (betterPathAvailable) in
if (betterPathAvailable) {
NSLog("A better path is availble")
} else {
NSLog("No better path is available")
}
}
connection!.start(queue: .global())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment