简体   繁体   English

没有在 swift 类中调用 AsyncSocket 回调

[英]AsyncSocket callbacks not being called in a swift class

GCDAsyncSocket delegates not being called in swift class, but works very well in UIViewController class. GCDAsyncSocket 委托不在 swift 类中被调用,但在 UIViewController 类中工作得很好。 Below is my custom class code, in this class connect function will start socket connection and it's delegate will never called.下面是我的自定义类代码,在这个类中 connect 函数将启动套接字连接并且它的委托永远不会被调用。 I search on net and also on GCDAsyncSocket github repo but no success.我在网上和 GCDAsyncSocket github repo 上搜索,但没有成功。

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()

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 (eg "rxSocket") is not persisting beyond the call to connect()回调不起作用的原因很可能是您的实例化对象(例如“rxSocket”)在调用 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.一旦函数返回,常量 rxSocket 就变得无效,因为 rxSocket 只对函数是本地的,一旦超出范围就会被销毁。

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.解决方案是使 rxSocket 成为一个对象,该对象在调用 connect() 之后仍然存在,因此当 GDCAsyncSocket 调用回调函数时它仍然可用。

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")
    }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM