Search code examples
iosswift5p2pmultipeer-connectivity

MultiPeerConnectivity programmatically


I am making an application that transfers data between phones. how can I connect and accept a connection request from another device programmatically without MCBrowserViewController


Solution

  • I worked in multipeer connectivity framework and I hope I am able to help you.

    Step 1:

    You can use MCNearbyServiceAdvertiser for advertising yourself with your custom service-type like:

    let advertiser = MCNearbyServiceAdvertiser.init(peer: *peerID*, discoveryInfo: *dict*, serviceType: *custom_service_type*)
    

    set the delegate and start advertising yourself.

    Step 2:

    In other device , user MCNearbyServiceBrowser

    let browser = MCNearbyServiceBrowser.init(peer: *peerID*,serviceType: *custom_service_type*)
    

    set the delegate and start browsing for peer users.

    Step 3:

    When the browser finds some users in the same Wi-fi network and with same service type, you will get a delegate callback to

    func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?)
    

    Step 4:

    Manually try connecting to the peer

    browser.invitePeer(*peerID*, to: *session*, withContext: nil, timeout: 30)
    

    Step 5:

    In the first device, you will get a callback in delegate method saying that a peer device wants to connect

    func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void)
    

    call the completion handler with a true value and share your session

    invitationHandler(true,*session*)
    

    Here we don't need any user interaction. All are done programmatically(which is your requirement).

    Note:

    1. The service type of both the advertiser and browser must be the same.
    2. Make sure you confirm to the protocols(MCNearbyServiceAdvertiserDelegate,MCNearbyServiceBrowserDelegate).
    3. Make sure you have initialised a session properly before all these steps.