capacitor-mdns-discovery 0.0.4 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2,7 +2,8 @@ import Foundation
|
|
|
2
2
|
import Network
|
|
3
3
|
|
|
4
4
|
@objc public class MdnsDiscovery: NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
|
|
5
|
-
|
|
5
|
+
// One browser per service type so we can scan multiple types at once.
|
|
6
|
+
private var browsers: [String: NetServiceBrowser] = [:]
|
|
6
7
|
private var services: [String: NetService] = [:]
|
|
7
8
|
|
|
8
9
|
@objc public var onDeviceFound: (([String: Any]) -> Void)?
|
|
@@ -10,25 +11,46 @@ import Network
|
|
|
10
11
|
@objc public var onError: (([String: Any]) -> Void)?
|
|
11
12
|
|
|
12
13
|
@objc public func startDiscovery(serviceType: String) {
|
|
13
|
-
stopAll()
|
|
14
|
-
|
|
15
14
|
let normalizedType = serviceType.hasSuffix(".") ? serviceType : "\(serviceType)."
|
|
16
15
|
|
|
16
|
+
// If we're already browsing this type, do nothing.
|
|
17
|
+
if browsers[normalizedType] != nil {
|
|
18
|
+
return
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
let browser = NetServiceBrowser()
|
|
18
22
|
browser.delegate = self
|
|
19
|
-
|
|
20
|
-
|
|
23
|
+
browsers[normalizedType] = browser
|
|
21
24
|
browser.searchForServices(ofType: normalizedType, inDomain: "local.")
|
|
22
25
|
}
|
|
23
26
|
|
|
24
27
|
@objc public func stopDiscovery(serviceType: String?) {
|
|
25
|
-
|
|
28
|
+
guard let serviceType else {
|
|
29
|
+
stopAll()
|
|
30
|
+
return
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
let normalizedType = serviceType.hasSuffix(".") ? serviceType : "\(serviceType)."
|
|
34
|
+
if let browser = browsers[normalizedType] {
|
|
35
|
+
browser.stop()
|
|
36
|
+
browser.delegate = nil
|
|
37
|
+
browsers.removeValue(forKey: normalizedType)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Stop monitoring any services for this type.
|
|
41
|
+
let keysToRemove = services.keys.filter { $0.hasSuffix(".\(normalizedType)") }
|
|
42
|
+
for key in keysToRemove {
|
|
43
|
+
services[key]?.stopMonitoring()
|
|
44
|
+
services.removeValue(forKey: key)
|
|
45
|
+
}
|
|
26
46
|
}
|
|
27
47
|
|
|
28
48
|
@objc public func stopAll() {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
49
|
+
browsers.values.forEach {
|
|
50
|
+
$0.stop()
|
|
51
|
+
$0.delegate = nil
|
|
52
|
+
}
|
|
53
|
+
browsers.removeAll()
|
|
32
54
|
services.values.forEach { $0.stopMonitoring() }
|
|
33
55
|
services.removeAll()
|
|
34
56
|
}
|
|
@@ -93,6 +115,7 @@ import Network
|
|
|
93
115
|
}
|
|
94
116
|
|
|
95
117
|
private func serviceKey(for service: NetService) -> String {
|
|
96
|
-
|
|
118
|
+
// Include type so services don't collide across browsers.
|
|
119
|
+
return "\(service.name).\(service.type)"
|
|
97
120
|
}
|
|
98
121
|
}
|