Categories
Uncategorized

A functional wrapper for Apple’s MultipeerConnectivity framework.

PeerConnectivity is a framework that I wrote for simplifying the code needed to write Bluetooth/Wifi networking across iOS devices. It it currently published on Cocopods and is also available for download via Carthage.

If you have ever used Apple’s MultipeerConnectivity framework you know you are in for a world of hurt. There are so many moving parts that it quickly becomes difficult to manage large networking operations between devices. As I was using it in a larger application I began writing wrappers to encapsulate the functionality of the framework and to keep it contained while remaining accessible. Thus… PeerConnectivity was born.

Setup Connection Manager

Setting up a connection manager to automatically find and connect with nearby devices is as easy as passing in the specified service type (similar to channel).

let pcm = PeerConnectionManager(serviceType: "local")

Starting/Stopping

Start and stop with a single command.

pcm.start()
// Session active
pcm.stop()
// Session inactive

Sending Events to Peers

Sending events is as simple as creating JSON packets and passing them to the network or specified peer.

let event: [String: Any] = [
    "EventKey" : Date()
]
// Sends to all connected peers
pcm.sendEvent(event)
// Access the connected peers to send to specific peer devices
if let somePeerThatIAmConnectedTo = pcm.connectedPeers.first {
   pcm.sendEvent(event, toPeers: [somePeerThatIAmConnectedTo])
}

Listening for Events

Register event listeners to respond to incoming peer events.

// Listen to an event
pcm.observeEventListenerFor("someEvent") { (eventInfo, peer) in
    print("Received event \(eventInfo) from \(peer.displayName)")
    guard let date = eventInfo["eventKey"] as? Date else { return }
    print(date)
}
// Stop listening to an event
pcm.removeListenerForKey("SomeEvent")

This makes for an extremely lightweight networking syntax that makes implementing mesh-networking in your app simple. Enjoy 😸.

Leave a Reply