Do I need to set an entitlement or something, or have I missed a point somewhere?
(iOS 13, Xcode 11.7, SwiftUI)
Code Block var connection: NWConnection? var hostUDP: NWEndpoint.Host = "239.255.250.78" var portUDP: NWEndpoint.Port = 4002 func start() { print("UDP Provider has started") self.connectToUDP(hostUDP, portUDP) } func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) { let messageToUDP = "ANNOUNCE" connection = NWConnection(host: hostUDP, port: portUDP, using: .udp) connection?.stateUpdateHandler = { (newState) in switch (newState) { case .ready: print("State: Ready\n") self.sendUDP(messageToUDP) self.receiveUDP() case .setup: print("State: Setup\n") case .cancelled: print("State: Cancelled\n") case .preparing: print("State: Preparing\n") default: print("ERROR! State not defined!\n") } } connection?.start(queue: .global()) } func sendUDP(_ content: String) { let contentToSendUDP = content.data(using: String.Encoding.utf8) connection?.send(content: contentToSendUDP, 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!)") } }))) } func receiveUDP() { connection?.receiveMessage { (data, context, isComplete, error) in if (isComplete) { print("Receive is complete") if (data != nil) { let backToString = String(decoding: data!, as: UTF8.self) print("Received message: \(backToString)") } else { print("Data == nil") } } } }
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"