How to create singleton for the WebSocket (Starscream)?

1k views Asked by At

I am trying to create a singleton with WebSocket functionality and I just don't know why it's not working

This is my singleton extension:

import Starscream

extension WebSocketManager: WebSocketDelegate {
func websocketDidConnect(socket: WebSocket) {
    print("websocket is connected")
}

func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
    if let e = error {
        print("websocket is disconnected: \(e.localizedDescription)")
    } else {
        print("websocket disconnected")
    }
}

func websocketDidReceiveMessage(socket: WebSocket, text: String) {
    print("Received text: \(text)")
}

func websocketDidReceiveData(socket: WebSocket, data: Data) {
    print("Received data: \(data.count)")
}}

My singleton:

final class WebSocketManager: NSObject {
static let sharedInstance = WebSocketManager()
public var socket = WebSocket(url: URL(string: "ws://t-w-a.herokuapp.com/new")!)

private override init() {
    super.init()
    // testing connection of the socket
}

func establishConnection() {
    socket.connect()
}

func closeConnection() {
    socket.disconnect()
}}

When I am trying to connect the server just nothing happens. Here is my controller:

class ChatViewController: UIViewController {

@IBOutlet weak var typeText: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    WebSocketManager.sharedInstance.establishConnection()
}}
1

There are 1 answers

1
AudioBubble On

I've found problem, I just forgot to assign socket variable with the delegate