PeerConnectivity is meant to have a lightweight easy to use syntax, be extensible and flexible, and handle the heavy lifting and edge cases of the MultipeerConnectivity framework quietly in the background.
🔌 Blog post https://goo.gl/HJcMbE
Add PeerConnectivity as a Swift Package dependency:
.package(url: "https://github.com/rchatham/PeerConnectivity.git", from: "0.6.0")Use the core networking product for UIKit-free peer connectivity:
.product(name: "PeerConnectivity", package: "PeerConnectivity")Add the UI helper product only when you need UIKit browser view controller support:
.product(name: "PeerConnectivityUI", package: "PeerConnectivity")CocoaPods and Carthage are no longer the recommended distribution paths for new releases.
var pcm = PeerConnectionManager(serviceType: "local")
// Start
pcm.start()
// Stop
// - You should always stop the connection manager
// before attempting to create a new one
pcm.stop()
// Can join chatrooms using PeerConnectionType.automatic, .inviteOnly, and .custom
// - .automatic : automatically searches and joins other devices with the same service type
// - .inviteOnly : provides advertiser assistant behavior; import PeerConnectivityUI for browserViewController support
// - .custom : no default behavior is implemented
// The manager can be initialized with a contructed peer representing the local user
// with a custom displayName
pcm = PeerConnectionManager(serviceType: "local", connectionType: .automatic, displayName: "I_AM_KING")
// Start again at any time
pcm.start() {
// Do something when finished starting the session
}UIKit browser view controller support lives in the separate PeerConnectivityUI SwiftPM product:
import PeerConnectivity
import PeerConnectivityUI
let pcm = PeerConnectionManager(serviceType: "local", connectionType: .inviteOnly)
let browserViewController = pcm.browserViewController { event in
switch event {
case .didFinish, .wasCancelled, .none:
break
}
}let event: [String: Any] = [
"EventKey" : Date()
]
// Sends to all connected peers
pcm.sendEvent(event)
// Use this to access the connectedPeers
let connectedPeers: [Peer] = pcm.connectedPeers
// Events can be sent to specific peers
if let somePeerThatIAmConnectedTo = connectedPeers.first {
pcm.sendEvent(event, toPeers: [somePeerThatIAmConnectedTo])
}// Listen to an event
pcm.observeEventListenerForKey("someEvent") { (eventInfo, peer) in
print("Received some event \(eventInfo) from \(peer.displayName)")
guard let date = eventInfo["eventKey"] as? Date else { return }
print(date)
}
// Stop listening to an event
pcm.removeListenerForKey("SomeEvent")Icon from the Noun Project.
-
Check out the Demo project and Playground for examples to help you take you're app to the next level!!!
-
Read the docs!
