如何为WebSocket(红蜘蛛)创建单例?

时间:2017-05-23 23:44:32

标签: swift3 websocket singleton starscream

我正在尝试创建一个具有WebSocket功能的单例,我只是不知道为什么它不起作用

这是我的单身扩展名:

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)")
}}

我的单身人士:

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()
}}

当我尝试连接服务器时,没有任何反应。 这是我的控制器:

class ChatViewController: UIViewController {

@IBOutlet weak var typeText: UITextField!

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

1 个答案:

答案 0 :(得分:1)

我发现问题,我只是忘了用委托

分配socket变量