UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to create a peer-to-peer network using the multipeer connectivity framework

Swift version: 5.6

Paul Hudson    @twostraws   

The MultipeerConnectivity framework is designed to allow ad hoc data transfer between devices that are in close proximity. The connection is started managed for you by iOS, but you're responsible for presenting useful interface to your users and for understanding the data that is being sent and received.

First things first, import the MultipeerConnectivity framework:

import MultipeerConnectivity

Now define these three properties to hold the multipeer session information:

var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!

The peer ID is simply the name of the current device, which is useful for identifying who is joining a session. We're just going to use the current device's name when creating our connection, but we're also going to require encryption. Add this to your viewDidLoad() method:

peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
mcSession.delegate = self

You will need to tell iOS that your view controller conforms to the MCSessionDelegate and MCBrowserViewControllerDelegate delegates, like this:

class ViewController: UIViewController, MCSessionDelegate, MCBrowserViewControllerDelegate {
    // your view controller here
}

Conforming to those two delegates means implementing quite a few methods. Fortunately, five of them are super simple because three are empty and the other two just dismiss a view controller. Add this code now:

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {

}

func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {

}

func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {

}

func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true)
}

func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true)
}

Next comes a slightly harder method: you need to do something when clients connect or disconnect. That something could just be "I don't care; do nothing," or it might be where you show a message on the screen to tell your user. Here's a basic version that just prints out a status message to the Xcode log:

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
    switch state {
    case MCSessionState.connected:
        print("Connected: \(peerID.displayName)")

    case MCSessionState.connecting:
        print("Connecting: \(peerID.displayName)")

    case MCSessionState.notConnected:
        print("Not Connected: \(peerID.displayName)")
    }
}

Time for the important stuff: sending and receiving data. Now, obviously the data you will send and receive depends on what your app does, so you will need to customize this code to fit your needs. In the example I'm going to give, we'll use sending and receiving images, but you could just as easily send strings or anything else.

So, here's how to encode an image into a Data then send that to all connected peers:

func sendImage(img: UIImage) {
    if mcSession.connectedPeers.count > 0 {
        if let imageData = img.pngData() {
            do {
                try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable)
            } catch let error as NSError {
                let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
            }
        }
    }
}

To receive that on the other side, you need a method like this:

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    if let image = UIImage(data: data) {
        DispatchQueue.main.async { [unowned self] in
            // do something with the image
        }
    }
}

Note that I've explicitly pushed the work to the main thread so that you're safe to do UI work.

All that remains now is to either host a session or join a session. Add these two methods to your code, then call whichever one you need:

func startHosting(action: UIAlertAction!) {
    mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "hws-kb", discoveryInfo: nil, session: mcSession)
    mcAdvertiserAssistant.start()
}

func joinSession(action: UIAlertAction!) {
    let mcBrowser = MCBrowserViewController(serviceType: "hws-kb", session: mcSession)
    mcBrowser.delegate = self
    present(mcBrowser, animated: true)
}

Note: to test this code you'll need either two iOS devices or one device and the simulator.

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.0 – see Hacking with Swift tutorial 25

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.