Created
February 4, 2020 15:43
-
-
Save Yerazhas/9020296da5d8f9f19c8ffca2105c5b8c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SocketIO | |
class MessagesSocketIOManager: CFMessagesSocket { | |
weak var delegate: CFMessagesSocketDelegate? | |
private let manager: SocketManager | |
private let socket: SocketIOClient | |
init(urlString: String) { | |
self.manager = SocketManager(socketURL: URL(string: urlString)!, config: [.log(true), .compress]) | |
self.socket = manager.defaultSocket | |
socket.on(clientEvent: .connect) { (_, _) in | |
self.observeMessages() | |
} | |
} | |
func connect() { | |
print("connect") | |
} | |
func disconnect() { | |
print("disconnect") | |
} | |
func sendMessage(message: String) { | |
guard let data = message.data(using: .utf8) else { return } | |
socket.emit("send", data) | |
} | |
func sendMessage(data: Data) { | |
socket.emit("send", data) | |
} | |
func observeMessages() { | |
socket.on("messages") { (data, ack) in | |
if let dict = data[0] as? [String: Any] { | |
if let resultDict = dict["result"] as? [[String: Any]] { | |
if JSONSerialization.isValidJSONObject(resultDict) { | |
do { | |
let data = try JSONSerialization.data(withJSONObject: resultDict, options: []) | |
self.delegate?.didReceiveData(data: data) | |
} catch { | |
self.delegate?.didReceiveError(error: error) | |
} | |
} | |
} else if let resultStr = dict["result"] as? String { | |
self.delegate?.didReceiveMessage(message: resultStr) | |
} | |
} else { | |
let error = MessageError.noData | |
self.delegate?.didReceiveError(error: error) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment