GCDAsyncSocket in Swift

旧街凉风 提交于 2019-12-03 15:35:34
Soaple

I also had a problem, and I solve it like below.

You have to make class inherit from NSObject.

import Foundation
import CocoaAsyncSocket

public class MySocket: NSObject, AsyncSocketDelegate {

    var mSocket: AsyncSocket!

    override init() {
        super.init()

        let mSocket = AsyncSocket.init(delegate: self)
        do {
            print("Connecing to socket server...")
            try mSocket.connectToHost("google.com", onPort: 80)
        } catch let error {
            print(error)
        }
    }

    @objc public func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        print("success")
    }

}

Below link can help you.

Implement AsyncSocket callbacks in a swift class

FYI, if anyone else is running into the problem where didConnectToHost is not being called and seem to have tried everything else: I realized I was initializing my socket service class in my AppDelegate. When I moved the code elsewhere it worked and the callback was called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!