-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
BonsoirAction.swift
82 lines (69 loc) · 2.54 KB
/
BonsoirAction.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#if canImport(Flutter)
import Flutter
#endif
#if canImport(FlutterMacOS)
import FlutterMacOS
#endif
#if canImport(os)
import os
#endif
/// Represents a Bonsoir action (broadcast or discovery).
@available(iOS 13.0, macOS 10.15, *)
class BonsoirAction: NSObject, FlutterStreamHandler {
/// The action identifier.
private let id: Int
/// The action name.
private let action: String
/// Whether to print debug logs.
private let printLogs: Bool
/// Triggered when this instance is being disposed.
private let onDispose: () -> Void
/// The current event channel.
private var eventChannel: FlutterEventChannel?
/// The current event sink.
private var eventSink: FlutterEventSink?
/// Initializes this class.
public init(id: Int, action: String, printLogs: Bool, onDispose: @escaping () -> Void, messenger: FlutterBinaryMessenger) {
self.id = id
self.action = action
self.printLogs = printLogs
self.onDispose = onDispose
super.init()
eventChannel = FlutterEventChannel(name: "\(SwiftBonsoirPlugin.package).\(action).\(id)", binaryMessenger: messenger)
eventChannel?.setStreamHandler(self)
}
/// Called by the event channel when ready to list.
func onListen(withArguments arguments: Any?, eventSink: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = eventSink
return nil
}
/// Called by the event channel when cancelled.
func onCancel(withArguments arguments: Any?) -> FlutterError? {
eventSink = nil
return nil
}
/// Triggered when a success occurs.
internal func onSuccess(_ eventId: String, _ message: String, _ service: BonsoirService? = nil) {
log(message)
eventSink?(SuccessObject(id: eventId, service: service).toJson())
}
/// Triggered when an error occurs.
internal func onError(_ message: String, _ details: Any? = nil) {
log(message)
eventSink?(FlutterError.init(code: "\(action)Error", message: message, details: details))
}
/// Disposes the current class instance.
public func dispose() {
onDispose()
}
/// Logs a given message.
internal func log(_ message: String) {
if (printLogs) {
#if canImport(os)
os_log("[%d] %s", log: OSLog(subsystem: SwiftBonsoirPlugin.package, category: action), type: OSLogType.info, id, message)
#else
NSLog("\n[\(id)] \(message)")
#endif
}
}
}