I would like to write an iOS Swift app that connects to an UDP server locally.
Here is the code I wrote using a library called CocoaAsyncSocket, however when I run it it does crash.
I haven't found any similar high level API in Apple. The only thing I found is this documentation which suggest to us a higher level API.
Would you be able to point me towards a better library or towards resolving the bug I get?
import UIKit
import CocoaAsyncSocket
class OutputSocket: NSObject, GCDAsyncUdpSocketDelegate {
var serverIP = "127.0.0.1"
var port:UInt16 = 10000
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do {
try socket.bind(toPort: self.port)
}
catch {
print("binding error: ", error.localizedDescription)
}
let addressData = serverIP.data(using: String.Encoding.utf8)
do {
try socket.connect(toAddress: addressData!)}
catch
{
print("connecting error: ", error.localizedDescription)
}
do {
try socket.beginReceiving()
}
catch {
print("connecting error: ", error.localizedDescription)
}
}
func send(message:String){
let data = message.data(using: String.Encoding.utf8)
let addressData = serverIP.data(using: String.Encoding.utf8)
socket.send(data!, toAddress: addressData!, withTimeout: 2, tag: 0)
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
print("didConnectToAddress");
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
print("didNotConnect \(error)")
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
print("didSendDataWithTag")
}
func udpSocket(_ sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: Error!) {
print("didNotSendDataWithTag")
}
}
Error description:
When I run it it crashes here:
EDIT:
I have removed the IP address from the equation and now, when I run the following code I get "didNotSendDataWithTag":
let data = message.data(using: String.Encoding.utf8)
socket.send(data!, withTimeout: 2, tag: 0)
Any idea why?
