我是iOS的菜鸟,在这里我想做一个后台WebSocket来处理来自服务器的所有事件。
import UIKit
import Starscream
class WebSocketLink: WebSocketDelegate{
var isConnected:Bool = false
func connect(){
var request = URLRequest(url: URL(string: "\(WEBSOCKET_HOST)")!)
request.timeoutInterval = 5
request.setValue("sessionid=\(ACCESS_TOKEN)", forHTTPHeaderField: "Cookie")
SOCKET = WebSocket(request: request)
SOCKET?.delegate = self
SOCKET?.connect()
}
func disconnect() {
SOCKET?.disconnect()
}
func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event{
case .connected(let headers):
isConnected = true
print("websocket is connected: \(headers)")
case .disconnected(let reason, let code):
isConnected = false
print("websocket is disconnected: \(reason) with code: \(code)")
case .text(let string):
print("Received text: \(string)")
case .binary(let data):
print("Received data: \(data.count)")
case .ping(_):
break
case .pong(_):
break
case .viabilityChanged(_):
break
case .reconnectSuggested(_):
break
case .cancelled:
isConnected = false
case .error(let error):
isConnected = false
print(error ?? "x")
}
}
}
这里的 SOCKET 是一个全局变量:
var SOCKET:WebSocket? = nil
我在 App init 函数中连接 WebSocket:
init(){
let link = WebSocketLink()
link.connect()
}
然后应用程序无法在 didReceive 函数中打印任何内容。我已经测试了 WebSocket 已连接并且它可以发送和接收(通过 javascript 测试代码)。如何通过 didReceive 函数从服务器接收数据?或者有什么更好的方法来制作后台 websocket 来处理来自服务器的所有事件?先感谢您!!!!