capacitor-sockets/ios/Sources/SocketsPlugin/Sockets.swift
2024-10-03 01:22:10 -04:00

66 lines
1.8 KiB
Swift

import Foundation
enum SocketState:String {
case connecting = "connecting"
case connected = "connected"
case disconnected = "disconnected"
}
@objc public class Sockets: NSObject, SocketDelegate {
private var sockets: [Socket] = []
private weak var plugin: SocketsPlugin?
@objc public init(plugin: SocketsPlugin? = nil) {
self.plugin = plugin
}
func didChangeState(socket: String, state: SocketState) {
self.plugin?.notifyListeners("state", data: [
"id": socket,
"state": state.rawValue
])
}
func didReceiveMessage(socket: String, message: String) {
self.plugin?.notifyListeners("message", data: [
"id": socket,
"message": message
])
}
@objc public func create(id: String, host: String, port: Int, useTLS: Bool = false, acceptInvalidCertificates: Bool = false) -> Socket {
let socket = Socket(id: id, host: host, port: port, useTLS: useTLS, acceptInvalidCertificates: acceptInvalidCertificates)
socket.delegate = self
sockets.append(socket)
return socket
}
@objc public func connect(id: String) {
if let socket = self.socket(with: id) {
socket.connect()
}
}
@objc public func send(id: String, message: String) {
if let socket = self.socket(with: id) {
socket.write(message)
}
}
@objc public func disconnect(id: String) {
if let socket = self.socket(with: id) {
socket.disconnect()
}
}
@objc func socket(with id: String) -> Socket? {
for socket in self.sockets {
if (socket.id == id) {
return socket
}
}
return nil
}
}