我正在使用Swift开发一个iOS应用程序,它通过套接字连接到Android设备。我已经实现了红蜘蛛并且能够连接到另一个设备。我的问题是,当我在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)")
}
}
最佳答案
您需要将其作为类属性,否则它将在离开viewDidLoad方法时被释放。
关于ios - 红蜘蛛的socket.isConnected总是返回false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36792175/