2021-06-12 16:03:29 +03:00
|
|
|
// Copyright © 2021 Encrypted Ink. All rights reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import MultipeerConnectivity
|
|
|
|
|
|
|
|
private let serviceIdentifier = "connector"
|
|
|
|
private let queue = DispatchQueue(label: serviceIdentifier, qos: .default)
|
2021-06-12 17:39:42 +03:00
|
|
|
private var acceptedLinks = Set<String>()
|
2021-06-12 16:03:29 +03:00
|
|
|
|
2021-06-12 16:08:41 +03:00
|
|
|
protocol NearbyConnectivityDelegate: AnyObject {
|
|
|
|
func didFind(link: String)
|
|
|
|
}
|
|
|
|
|
2021-06-12 16:03:29 +03:00
|
|
|
class NearbyConnectivity: NSObject {
|
|
|
|
|
2021-06-12 16:08:41 +03:00
|
|
|
private weak var connectivityDelegate: NearbyConnectivityDelegate?
|
2021-06-12 16:03:29 +03:00
|
|
|
private var devicePeerID: MCPeerID!
|
|
|
|
private var serviceBrowser: MCNearbyServiceBrowser!
|
|
|
|
|
2021-06-12 16:08:41 +03:00
|
|
|
init(delegate: NearbyConnectivityDelegate) {
|
2021-06-12 16:03:29 +03:00
|
|
|
super.init()
|
2021-06-12 16:08:41 +03:00
|
|
|
connectivityDelegate = delegate
|
2021-06-12 16:03:29 +03:00
|
|
|
devicePeerID = MCPeerID(displayName: UUID().uuidString)
|
|
|
|
|
|
|
|
serviceBrowser = MCNearbyServiceBrowser(peer: devicePeerID, serviceType: serviceIdentifier)
|
|
|
|
serviceBrowser.delegate = self
|
|
|
|
|
|
|
|
autoConnect()
|
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
|
|
|
stopBrowsing()
|
|
|
|
}
|
|
|
|
|
|
|
|
private func stopBrowsing() {
|
|
|
|
serviceBrowser.stopBrowsingForPeers()
|
|
|
|
}
|
|
|
|
|
|
|
|
private func autoConnect() {
|
|
|
|
queue.async { [weak self] in
|
|
|
|
self?.serviceBrowser.startBrowsingForPeers()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Browser Delegate
|
|
|
|
extension NearbyConnectivity: MCNearbyServiceBrowserDelegate {
|
|
|
|
|
|
|
|
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) {
|
2021-06-12 17:39:42 +03:00
|
|
|
guard let info = info, let link = info["wclink"], !acceptedLinks.contains(link) else { return }
|
|
|
|
acceptedLinks.insert(link)
|
2021-06-12 16:08:41 +03:00
|
|
|
DispatchQueue.main.async { [weak connectivityDelegate] in
|
|
|
|
connectivityDelegate?.didFind(link: link)
|
|
|
|
}
|
2021-06-12 16:03:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { }
|
|
|
|
|
|
|
|
}
|