2

I want to establish a bluetooth connection between 2 iPhones with a GKSession without GKPeerPickerController and without pushing any "connect button" on both sides.

I'm using the following code:

currentSessionAuto = [[GKSession alloc] initWithSessionID: @"instant-friend-auto" 
currentSessionAuto.delegate = self;
currentSessionAuto.available = YES;
currentSessionAuto.disconnectTimeout = 5;
[currentSessionAuto setDataReceiveHandler: self withContext:nil];

When the application is starting on both sides, the - (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state is called on both sides with the state "GKPeerStateAvailable".

With a "classic" app, a popup is displayed on both side to ask for connection and most of the time, both "users" does not click on the connect button on the same time.

If I want to have an "Automatic connection" I need a mechanism to only initiate the session on 1 side, because without this mechanism two sessions will be initiated and errors occur.

Any idea / help ?

halfer
  • 19,824
  • 17
  • 99
  • 186
fvisticot
  • 7,936
  • 14
  • 49
  • 79

2 Answers2

4

Take a look at GKSessionP2P, a demo app that illustrates the ad-hoc networking features of GKSession. The app both advertises itself on the local network and automatically connects to available peers, establishing a peer-to-peer network.

Marco
  • 6,692
  • 2
  • 27
  • 38
  • Tx for the link. I have approximatively the same code... I do not understand why a tempo (0.5s) is used in the code (in the available state) ? – fvisticot Feb 02 '12 at 17:52
  • Fair question. It seems to connectToPeer more successfully after a 0.5s wait. – Marco Feb 02 '12 at 22:22
  • 1
    This timeout probably is there to give so the connection has a chance to establish behind the scenes before the table view updates. Timeouts like this are bad practice. – openfrog Nov 20 '12 at 22:50
1

Here's an idea: have the peer with the lowest peerID connect. You'll have to convert the PeerID string to an int and compare, but it should be a great tie breaker.

Mark Pauley
  • 1,445
  • 12
  • 11
  • Why would you want to do that? – openfrog Nov 20 '12 at 22:52
  • Because it would be a sure-fire way to choose which client is the one that initiates the connection. Only one of the numbers can be the low number (the peerID's can't be equal). Thus make the low one connect to the high one. This completely resolves OP's problem. Think about it. – Mark Pauley Nov 27 '12 at 18:36