websocket 如何在SwiftUI中使用 Redis 库

gijlo24d  于 2022-11-24  发布在  Swift
关注(0)|答案(1)|浏览(136)

这段代码来自一个基于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)
        }     }
67up9zun

67up9zun1#

我建议将委托 Package 在ObservableObject类中:

class WebSocket: NSObject, WebSocketDelegate, ObservableObject {
    var socket: WebSocket!
    @Published var event: WebSocketEvent?
    var isConnected: Bool = false
    let server = WebSocketServer()
    var token: String = ""
    func didReceive(event: WebSocketEvent, client: WebSocket) {
        self.event = event
    }
    func connect(request: URLRequest) {
        socket = WebSocket(request: request)
        socket.delegate = self
        socket.connect()
    }
}

然后在View中:

struct YourView: View {
    @StateObject var socketDelegate = WebSocket()
    var body: some View {
        //your view
            .onAppear {
                var request = URLRequest(url: URL(string: "wss://-----")!)
                request.timeoutInterval = 5
                request.setValue("https://-----", forHTTPHeaderField: "Origin")
                socketDelegate.connect(request: request)
            }.onChange(of: socketDelegate.event) { event in
                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)
                }
            }
    }
}

相关问题