Search code examples
swiftmultipeer-connectivitymcsession

MCSessionState changes from connecting to not connected state


Whenever I try to connect a peer using the Multipeer Connectivity Framework, the peer's state changes from MCSessionState.Connecting to MCSessionState.NotConnected.

Here are the order of events I run:

  1. The simulator advertises the service via an MCNearbyServiceAdvertiser.
  2. An iPhone browses for the service via an MCNearbyServiceBrowser.
  3. The iPhone finds the simulator and immediately invites it to a session via invitePeer(_:toSession:withContext:timeout:).
  4. Finally, the simulator accepts the invitation using advertiser(_:didReceiveInvitationFromPeer:withContext:invitationHandler:).

Notes:

  • Even though I'm not requiring security, I'm accepting any certificates sent over by clients in case that is the bug.

Here is the code I'm using:

import UIKit
import MultipeerConnectivity

class ViewController: UIViewController {
    var advertiser: MCNearbyServiceAdvertiser!
    var browser: MCNearbyServiceBrowser!
    var session: MCSession!

    override func viewDidLoad() {
        super.viewDidLoad()
        let localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
        session = MCSession(peer: localPeerID, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.None)
        session.delegate = self
    }

    @IBAction func hostTapped(sender: AnyObject) {
        let localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
        advertiser = MCNearbyServiceAdvertiser(peer: localPeerID, discoveryInfo: nil, serviceType: "abc")
        advertiser.delegate = self
        print("started advertising")
        advertiser.startAdvertisingPeer()
    }

    @IBAction func connectTapped(sender: AnyObject) {
        let localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
        browser = MCNearbyServiceBrowser(peer: localPeerID, serviceType: "abc")
        browser.delegate = self
        print("started searching")
        browser.startBrowsingForPeers()
    }
}

extension ViewController: MCNearbyServiceAdvertiserDelegate {
    func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) {
        print("accepting invitation from \(peerID.displayName)")
        invitationHandler(true, session)
    }

    func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) {
        print("did not start advertising \(error)")
    }
}

extension ViewController: MCSessionDelegate {
    func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
        print("\(peerID.displayName) changed state: \(state.toString())")
    }

    func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {

    }

    func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {

    }

    func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {

    }

    func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {

    }

    func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void) {
        certificateHandler(true)
    }
}

extension ViewController: MCNearbyServiceBrowserDelegate {
    func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
        print("found \(peerID.displayName), inviting to session")
        browser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 30)
    }

    func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
        print("lost \(peerID.displayName)")
    }
}

extension MCSessionState {
    func toString() -> String {
        switch self {
        case .Connected:    return "Connected"
        case .Connecting:   return "Connecting"
        case .NotConnected: return "Not Connected"
        }
    }
}

There is a similar question here, however, the code linked is old and can no longer be accessed. Furthermore, the problem was that the same session object was being used.


Solution

  • I was using different MCPeerID instances for the MCSession, MCNearbyServiceAdvertiser and MCNearbyServiceBrowser.

    To fix it, I created an MCPeerID instance variable:

    var localPeerID: MCPeerID?
    
    override func viewDidLoad() {
        // ...
        localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)
        // ...
    }
    

    ... and used it instead of creating them as local variables (let localPeerID = ...).

    It now goes from the connecting to connected state correctly.