I am building a framework in Swift that uses GCDAsyncSocket written in Objective-C.
The error I am receiving is:
Couldn't start socket: Error Domain=GCDAsyncSocketErrorDomain Code=1 "Attempting to accept without a delegate. Set a delegate first." UserInfo=0x61000026b940 {NSLocalizedDescription=Attempting to accept without a delegate. Set a delegate first.}
I have tried setting the delegate in the init method (shown below) and also tried setting it using the setDelegate method after initialization.
While debugging, I have verified that the setDelegate code is getting called and that the value passed in (self
) actually contains a reference.
UPDATE: when I modify the GCDAsyncSocket.m to remove the __weak
keyword from the declaration of the delegate, it works, but I still so not understand why I should have to do that.
The line was: __weak id delegate
, changed to id delegate
Here is the class causing the problem:
class Server: GCDAsyncSocketDelegate
{
let boundHost:String?
let port:UInt16
var socket:GCDAsyncSocket?
init(boundHost: String?, port: UInt16)
{
if boundHost {
self.boundHost = boundHost!
}
self.port = port
println("Server created with host: \(self.boundHost) and port: \(self.port).")
}
convenience init(port:UInt16) {
self.init(boundHost: nil, port: port)
}
func startServer() -> Bool
{
if !socket
{
socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
}
var error:NSError?
if !socket!.acceptOnInterface(boundHost, port: port, error: &error)
{
println("Couldn't start socket: \(error)")
return false;
}
else
{
println("Listening on \(port).")
return true
}
}
func stopServer() -> Bool
{
if socket
{
socket!.disconnect()
return true
}
return false
}
func socket(sock:GCDAsyncSocket!, didAcceptNewSocket newSocket:GCDAsyncSocket!)
{
println("New socket received: \(newSocket)")
}
}