Multipeer Connectivity (part 2)

Peter FennemaiOSLeave a Comment

In part 1 of my series about the iOS  Multipeer Connectivity Framework I concluded that my solution to setup a session between 2 peers without user interaction was not working. This was caused by the mutual invitation issue: A peer  continues to invite the peer that it was already connected with.

In this post I wil come up with a solution for the mutual invitation issue. You can download the source code here.

The relevant snippet is in the MCNearbyServiceBrowserDelegate.

This method is called when a browser finds a peer. As soon as a browser has found a peer it invites the peer to connect. We are going to solve the mutual invitation issue by establishing a rule: “I will only invite a peer if the hash value of my peerID is smaller than the hash value of the other peerID”. Both peers will apply the same rule, so it is guaranteed that only one of them will send the invitation.

In code this can be expressed as follows:

Now let’s run a test

Again, we are going to connect the 2 peers, the simulator and my iPhone. Below you can see the result. I will show you the original logs, including the mutual invitation issue, and the logs with the fix described above, so you can compare them.

multipeer startup log

Log with mutual invitation issue

multipeer invite log

Log after application of the fix

 

As you can see steps 1 to 6 are exactly identical for both scenario’s. The big difference is at step 7. The log with the fix shows that the simulator does NOT invite the iPhone, thanks to the rule that comers the hash values of the peerID’s.  Therefore step 8 and 9 will not be triggered either, and the peers are connected.

Conclusion

We can conclude that we solved the mutual invitation issue. Peers can now create a session without any user interaction. I will continue with the Multipeer Connectivity Framework research  and will post new articles if I encounter further issues.

Leave a Reply

Your email address will not be published.