AsyncSocket callbacks not being called in a swift class
Asked Answered
L

2

7

GCDAsyncSocket delegates not being called in swift class, but works very well in UIViewController class. Below is my custom class code, in this class connect function will start socket connection and it's delegate will never called. I search on net and also on GCDAsyncSocket github repo but no success.

class RXSocket: NSObject,GCDAsyncSocketDelegate {

func connect() {

    let asyncSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())

    do {
        try asyncSocket?.connectToHost("www.google.com", onPort: 80)
    } catch _ as NSError {
    }

}


//MARK:- ASyncSocket Delegate

func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
    print("didConnectToHost")
}

func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
    print("didReceiveData")
}

func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
    print("socketDidDisconnect")
}

}

and in my view controller class

    let rxSocket = RXSocket()
    rxSocket.connect()
Load answered 2/6, 2016 at 12:49 Comment(6)
try to add @objc for each delegate func , also you need a strong reference to reference or it will be releaseManpower
tried but no luck.Load
check the fist comment i just editManpower
In swift, I don't know how to make strong ref. Please suggest.Load
Did you solved this question?Cheesecloth
Did you solved this question? I facing the same problemEstimable
G
2

I experienced the same problem and have solved it.

Your code sample is fine.

The reason for the call back not working is most likely that your instantiated object (e.g. "rxSocket") is not persisting beyond the call to connect()

Here is an example of code which will cause the problem

func testMyConnection() { 
    let rxSocket = RXSocket()
    rxSocket.connect()
}

The constant rxSocket becomes invalid once the function returns since rxSocket is local only to the function and is destroyed once it goes out of scope.

The solution is to make rxSocket an object which persists beyond the call to connect() so it is still available when the callback functions is called by GDCAsyncSocket.

Gascony answered 6/1, 2018 at 22:4 Comment(0)
M
0

try like this:

class RXSocket: NSObject,GCDAsyncSocketDelegate {
var asyncSocket: GCDAsyncSocket!
    func connect() {

    self.asyncSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)

    do {
        try asyncSocket.connect(toHost: "www.google.com", onPort: 80)
    } catch _ as NSError {
        print("Catch")
    }
    }
}
Manpower answered 2/6, 2016 at 13:3 Comment(1)
No explanation provided as to what's wrong with the code in the question and why it works OK in view controller. The answer does not solve the problem.Gascony

© 2022 - 2024 — McMap. All rights reserved.