iOS Reference Library Apple Developer
Search

Working with Sessions

This article explains how to use a GKSession object that was configured by the peer picker. For more information on how to configure the peer picker, see “Finding Peers with Peer Picker.”

A session receives two kinds of data: information about other peers, and data sent by connected peers. Your application provides a delegate to receive information about other peers and a data handler to receive information from other peers.

To use a session inside your application, first follow the steps found in “Finding Peers with Peer Picker,” then continue here.

  1. Implement the session delegate’s session:peer:didChangeState: method.

    The session’s delegate is informed when another peer changes states relative to the session. Most of these states are handled automatically by the peer picker. If your application implements its own user interface, it should handle all state changes. For now the application should react when users connect and disconnect from the network.

    - (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
    {
        switch (state)
        {
            case GKPeerStateConnected:
    // Record the peerID of the other peer.
    // Inform your game that a peer has connected.
            break;
            case GKPeerStateDisconnected:
    // Inform your game that a peer has left.
            break;
        }
    }
  2. Send data to other peers.

    - (void) mySendDataToPeers: (NSData *) data
    {
        [session sendDataToAllPeers: data withDataMode: GKSendDataReliable error: nil];
    }
  3. Receive data from other peers.

    - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
    {
        // Read the bytes in data and perform an application-specific action.
    }

    Your application can either choose to process the data immediately, or retain it and process it later within your application. Your application should avoid lengthy computations within this method.

  4. Clean up the session when you are ready to end the connection.

    [session disconnectFromAllPeers];
    session.available = NO;
    [session setDataReceiveHandler: nil withContext: nil];
    session.delegate = nil;
    [session release];



Last updated: 2009-05-28

Did this document help you? Yes It's good, but... Not helpful...