我正在使用通过套接字连接到Android设备的Swift开发iOS应用程序。我已经实施了Starscream并且能够连接到其他设备。我的问题是,当我在websocketDidConnect委托方法上打印一些东西时,它不会打印。另外,当我打印socket.isConnected时,它会输出false。请帮助我。谢谢。红蜘蛛的其他替代品也欢迎,谢谢!
这是我的代码:
import Starscream
class SettingsViewController: UIViewController, UITextFieldDelegate, WebSocketDelegate{
override func viewDidLoad() {
super.viewDidLoad()
let socket = WebSocket(url: NSURL(string: "ws://\(ipAddressTextField.text!):4000/")!)
socket.connect()
print("socket.isConnected \(socket.isConnected)") //this one is false
socket.onConnect = {
print("Connected...") // does not print
}
socket.onDisconnect = { (error: NSError?) in
print("websocket is disconnected: \(error?.localizedDescription)") // this one prints when I turn the wifi off
}
socket.onData = { (data: NSData) in
print("got some data: \(data.length)")
}
}
func websocketDidConnect(ws: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(ws: WebSocket, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(ws: WebSocket, data: NSData) {
print("Received data: \(data.length)")
}
}
答案 0 :(得分:0)
你需要将它作为一个类属性,否则它会在它离开viewDidLoad方法时被释放。