如何将标头附加到 URLSessionWebSocketTask

问题描述 投票:0回答:1

我需要将标头附加到 URLSessionWebSocketTask,我使用 URLRequest 完成此操作,但不知道其是否正确,因为我使用 WSS 连接而不是 HTTP。

var webSocketTask: URLSessionWebSocketTask!
    
    lazy var urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())

private var urlRequest: URLRequest = {
        var request = URLRequest(url: ApiUrl.socket.url)
        request.allHTTPHeaderFields = [
            "login" : "****",
            "passcode" : "****",
            "host" : "/",
            "accept-version" : "****"
        ]
        return request
    }()

public override init() {
        super.init()
        webSocketTask = urlSession.webSocketTask(with: urlRequest)
    }

而且我还需要订阅事件,但无法得到我需要做的事情。您可以看到下面的截图。

socket

ios swift websocket nsurlsession urlsession
1个回答
0
投票

你能试试这个代码吗?

class WebSocketManager: NSObject, URLSessionWebSocketDelegate {
    
    private var webSocketTask: URLSessionWebSocketTask!
    
    private lazy var urlSession: URLSession = {
        let configuration = URLSessionConfiguration.default
        return URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue())
    }()
    
    private var urlRequest: URLRequest {
        var request = URLRequest(url: ApiUrl.socket.url)
        request.allHTTPHeaderFields = [
            "login" : "****",
            "passcode" : "****",
            "host" : "/",
            "accept-version" : "****"
        ]
        return request
    }
    
    override init() {
        super.init()
        webSocketTask = urlSession.webSocketTask(with: urlRequest)
    }
    
    func connect() {
        webSocketTask.resume()
        
    }
    
}

您需要对您的问题进行更多调试。

extension WebSocketManager {
    
    func send(message: String) {
        let message = URLSessionWebSocketTask.Message.string(message)
        webSocketTask.send(message) { error in
            if let error = error {
                print("WebSocket sending error: \(error)")
            }
        }
    }
    
    func receive() {
        webSocketTask.receive { [weak self] result in
            switch result {
            case .failure(let error):
                print("WebSocket receiving error: \(error)")
            case .success(let message):
                switch message {
                case .string(let text):
                    print("Received text: \(text)")
                case .data(let data):
                    print("Received data: \(data)")
                @unknown default:
                    fatalError()
                }
                
                
                self?.receive()
            }
        }
    }
    
    func disconnect() {
        webSocketTask.cancel(with: .goingAway, reason: nil)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.