红蜘蛛不使用NSObject的继承

时间:2015-09-22 22:33:06

标签: ios

我尝试通过导入starscream类从NSObject创建一个类继承。但是从不调用websocketDidConnect。

不行!

class WebSocketService : NSObject , WebSocketDelegate {

var socket = WebSocket(url: NSURL(scheme: "wss", host:     GlobalUrl.WEB_SOCKET_URI, path: "/ws")!, protocols: ["chat", "superchat"])

override init() {
    super.init()
    socket.delegate = self
    socket.connect()
}    

当我使用UIViewcontroller的继承时,它工作正常。

class WebSocketService : UIViewController , WebSocketDelegate {

var socket = WebSocket(url: NSURL(scheme: "wss", host:     GlobalUrl.WEB_SOCKET_URI, path: "/ws")!, protocols: ["chat", "superchat"])

override init() {
    super.init()
    socket.delegate = self
    socket.connect()
}    
如果类是NSObject的话,

有什么问题吗?

1 个答案:

答案 0 :(得分:1)

它适用于NSObject,你只需要实现委托的所有方法(它们在Swift中不是可选的)。如果你没有看到websocketDidConnect被调用,那是因为它没有成功连接(可能是SSL错误或错误的URL等)。查看websocketDidDisconnect中的错误返回以找出问题所在。

class WebSocketService : NSObject , WebSocketDelegate {

var socket = WebSocket(url: NSURL(scheme: "wss", host: GlobalUrl.WEB_SOCKET_URI, path: "/ws")!, protocols: ["chat", "superchat"])

override init() {
    super.init()
    socket.delegate = self
    socket.connect()
}

func websocketDidConnect(socket: WebSocket) {

}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {

}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {

}
func websocketDidReceiveData(socket: WebSocket, data: NSData) {

}

}