Swift / iOS8:为websocket SocketIOCocoa创建共享实例

时间:2015-03-31 22:00:57

标签: ios swift websocket socket.io

我正在尝试使用此处的SocketIOCocoa库为websocket客户端创建一个共享实例: https://github.com/shuoli84/SocketIOCocoa

当在ViewController中使用来创建websocket客户端的新实例时,库工作得非常好 - 但我不知道如何设置共享实例。我尝试了什么:

import Foundation
import Alamofire

public class WebSocketClient:SocketIOSocket {


    public var WebSocket:SocketIOClient!

    func myWebSocketClient() -> SocketIOClient {

        if WebSocket != nil {
            return WebSocket
        } else {
        let uri = "\(CurrentConfiguration.serverURL)/socket.io/"

        var client = SocketIOClient(uri: uri, reconnect: true, timeout:3000)
        client.open()

        return client
        }
    }

由于我对协议/共享实例的使用还很陌生,所以我不知道我是否在正确的轨道上。至少当我想用它时它不起作用: var foo = WebSocketClient.myWebSocketclient()

这就是我在一个VC中的表现:

func newSocket() {

let uri = "\(CurrentConfiguration.serverURL)/socket.io/"

var client = SocketIOClient(uri: uri, reconnect: true, timeout:3000)
client.open()

var socket = client.socket("myNamespace") //join namespace


socket.event("customEvent", data: websocketRoomData){ (packet) -> Void in
                    }//emit event after join

socket.delegate = self
}


func socketOnEvent(socket: SocketIOSocket, event: String, data: AnyObject?) {

        switch event {
        case "returning from server event":
            println(event)
            let returnData = data as? NSArray

            //do stuff with return data

            doStuff(returnData!)

        default:
            println("Error: unrecognized Websockets Event received!")
    }
}

1 个答案:

答案 0 :(得分:2)

例如。 您可以在代码中的任何位置使用SocketSingleton.call。

let socket:SocketSingleton = SocketSingleton.call

socket.socketEmit()

class SocketSingleton: NSObject {

static let call = SocketSingleton()

let socket = SocketIOClient(socketURL: NSURL(string:"url")!)

override init() {
    super.init()
    addHandlers()
    socket.connect()
}

func addHandlers() {
    socket.on("message") { data, ack in

    }

    socket.on("reconnect") { data, ack in

    }

    socket.on("error") { data, ack in

    }

}
func socketEmit() {
    let msg = [:]
    var sendJson : NSString = ""
    do {
        let json = try NSJSONSerialization.dataWithJSONObject(msg, options: NSJSONWritingOptions.PrettyPrinted)
        let string = NSString(data: json, encoding: NSUTF8StringEncoding)
        sendJson = string! as NSString
    } catch let error as NSError {
        print(error.description)
    }

    socket.emit("message", sendJson)
}

}