Create repo, add feature to set username
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
//
|
||||
// CommunicationProvider.swift
|
||||
// Peered
|
||||
//
|
||||
// Created by Oskar Chybowski on 11/05/2025.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import MultipeerConnectivity
|
||||
|
||||
@Observable
|
||||
final class CommunicationProvider: NSObject, MCNearbyServiceBrowserDelegate {
|
||||
private let session: MCSession
|
||||
private let browser: MCNearbyServiceBrowser
|
||||
private let advertiser: MCNearbyServiceAdvertiser
|
||||
|
||||
private(set) var availablePeers: [MCPeerID] = []
|
||||
|
||||
init(id: String) {
|
||||
let id = MCPeerID(displayName: id)
|
||||
session = MCSession(peer: id, securityIdentity: nil, encryptionPreference: .required)
|
||||
browser = MCNearbyServiceBrowser(peer: id, serviceType: "peered")
|
||||
advertiser = MCNearbyServiceAdvertiser(
|
||||
peer: browser.myPeerID,
|
||||
discoveryInfo: [:],
|
||||
serviceType: "peered"
|
||||
)
|
||||
super.init()
|
||||
browser.delegate = self
|
||||
start()
|
||||
}
|
||||
|
||||
func start() {
|
||||
advertiser.startAdvertisingPeer()
|
||||
browser.startBrowsingForPeers()
|
||||
}
|
||||
|
||||
func stop() {
|
||||
browser.stopBrowsingForPeers()
|
||||
advertiser.stopAdvertisingPeer()
|
||||
}
|
||||
|
||||
func browser(
|
||||
_ browser: MCNearbyServiceBrowser,
|
||||
foundPeer peerID: MCPeerID,
|
||||
withDiscoveryInfo info: [String: String]?
|
||||
) {
|
||||
availablePeers.append(peerID)
|
||||
browser.invitePeer(peerID, to: session, withContext: nil, timeout: 30)
|
||||
}
|
||||
|
||||
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
|
||||
availablePeers.removeAll { id in
|
||||
id == peerID
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user