这段代码来自一个基于UIKit创建与 Redis 库的WebSocket连接的示例。如何在SwiftUI项目中使用它?
class ViewController: UIViewController, WebSocketDelegate {
var socket: WebSocket!
var isConnected: Bool = false
let server = WebSocketServer()
var token: String = ""
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "wss://-----")!)
request.timeoutInterval = 5
request.setValue("https://-----", forHTTPHeaderField: "Origin")
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()
}
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):
if string.contains("token expiring") { print("expiring"); socket.disconnect() }
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
handleError(error)
} }
1条答案
按热度按时间67up9zun1#
我建议将委托 Package 在
ObservableObject
类中:然后在
View
中: