Multipeer Connectivity Framework

Understanding principles and basic terms

 

  • Multiple network interface support (Bluetooth, WiFi, and ethernet)
  • Device detection
  • Security via encryption
  • Small message passing
  • File transfer

“The Multipeer Connectivity framework supports the discovery of services provided by nearby devices and supports communicating with those services through message-based data, streaming data, and resources (such as files). In iOS, the framework uses infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks for the underlying transport. In macOS and tvOS, it uses infrastructure Wi-Fi, peer-to-peer Wi-Fi, and Ethernet.”

  1. Peer: a peer (a device) was represented by an object of MCPeerID class
    import MultipeerConnectivity
    let myPeerID = MCPeerID(displayName: UIDevice.current.name)
    
  2. Session: ( MCSession) handles communication
  3. Browser: (MCNearbyServiceBrowser) Let your app search programmatically for nearby devices with apps that support sessions of a particular type
  4. Advertiser: (MCNearbyServiceAdvertiser) that allows a peer to discovers itself and indicates that others can invite it to a session
  5. Advertiser assistant: (MCAdvertiserAssistant) just like Advertiser but support basic UI that allows users to accept the invitation
  6. Discovery Phase and Session Phase:

If the app moves into the background, the framework stops advertising and browsing and disconnects any open sessions. Upon returning to the foreground, the framework automatically resumes advertising and browsing, but the developer must reestablish any closed sessions.

MCSession can be used to communicate with more than two devices. However, in my experience, the stablest way is that creating one for each peer your device is interacting with.

 

the issues that you may encounter

the mutual invitation issue

That happens because by default a peer will advertising and browsing at the same time. So as an advertiser device A receives an invitation from device B then accept it. But as a browser device A keep sending an invitation to device B that it was already connected with.
So I will come up with a solution that I will only invite a peer if the hash value of my peerID is smaller than the hash value of the other peerID:

   public func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) {
        // Invite the new peer to the session.
        let remotePeerName = peerID.displayName
        let myPeerID = session.myPeerID
        let shouldInvite = (myPeerID.displayName.compare(remotePeerName) == .orderedDescending)
        if shouldInvite {
            browser.invitePeer(peerID, to: session, withContext: nil, timeout: 10)
        }
    }

A nature, universe, science, music, love lover

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami