GKSession Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/GameKit.framework
Availability
Available in iOS 3.0 and later.
Deprecated in iOS 7.0.
Companion guide
Declared in
GKPublicConstants.h
GKSession.h
GKSessionError.h

Overview

A GKSession object provides the ability to discover and connect to nearby iOS devices using Bluetooth or Wi-fi.

Sessions primarily work with peers. A peer is any iOS device made visible by creating and configuring a GKSession object. Each peer is identified by a unique identifier, called a peer id (peerID) string. Your application can use a peerID string to obtain a user-readable name for a remote peer and to attempt to connect to that peer. Similarly, your session’s peer ID is visible to other nearby peers. After a connection is established, your application uses the remote peer’s ID to address data packets that it wants to send.

Peers discover other peers by using a unique string to identify the service they implement, called a session ID (sessionID). Sessions can be configured to broadcast a session ID (as a server), to search for other peers advertising with that session ID (as a client), or to act as both a server and a client simultaneously (as a peer.

Your application controls the behavior of a session through a delegate that implements the GKSessionDelegate protocol. The delegate is called when remote peers are discovered, when those peers attempt to connect to the session, and when the state of a remote peer changes. Your application also provides a data handler to the session so that the session can forward data it receives from remote peers. The data handler can be a separate object or the same object as the delegate.

When Bluetooth is turned on, Wi-Fi download speeds drastically decrease while the device is searching for other Bluetooth enabled devices. After the Bluetooth discovery time has completed, Wi-Fi speeds return to normal.

GKSession methods are thread-safe and may be called from any thread. However, the session always calls its delegate on the main thread.

Tasks

Creating a Session

Setting and Getting the Delegate

Searching for Other Peers

Obtaining Information About Other Peers

Connecting to a Remote Peer

Receiving Connections from a Remote Peer

Working with Connected Peers

Information About the Session

Properties

available

A Boolean value that determines whether or not the session wants to connect to new peers.

@property(getter=isAvailable) BOOL available
Discussion

When available is YES, the session is visible to other peers based on its sessionMode property. When available is set to NO, it remains connected to peers, but is no longer visible to nonconnected peers. The default is NO.

Typically, your application configures the session object with a delegate and data receiver, and then sets available to YES. When the delegate finishes connecting to peers, it should set the session’s available property to NO.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

delegate

The delegate of the session object.

@property(assign) id<GKSessionDelegate> delegate
Discussion

A session’s delegate is responsible for observing changes to other peers running with the same session ID. Your application must set a delegate before making your session known to other peers.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

disconnectTimeout

A time interval that expresses how long the session waits before it disconnects a nonresponsive peer.

@property(assign) NSTimeInterval disconnectTimeout
Discussion

The timeout is the waiting period before disconnecting a peer from the session. If a peer is disconnected, the delegate’s session:peer:didChangeState: method is called.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

displayName

The name of the user. (read-only)

@property(readonly) NSString *displayName
Discussion

The display name is transmitted to visible peers so that they can present a human-readable name for your session.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

peerID

A string that identifies your session to other peers. (read-only)

@property(readonly) NSString *peerID
Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

sessionID

A string used to filter the list of peers who are allowed to see your session. (read-only)

@property(readonly) NSString *sessionID
Discussion

The session ID is used by sessions configured as servers to advertise itself to other peers and by sessions configured as clients to search for compatible servers. The session ID should be the short name of an approved Bonjour service type.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

sessionMode

The mode the session uses to find other peers. (read-only)

@property(readonly) GKSessionMode sessionMode
Discussion

The session mode changes the behavior of the session when available is set to YES.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

Instance Methods

acceptConnectionFromPeer:error:

Called by the delegate to accept a connection request received from a remote peer.

- (BOOL)acceptConnectionFromPeer:(NSString *)peerID error:(NSError **)error
Parameters
peerID

The string identifying the peer that initiated the connection to the session.

error

If an error occurred when connecting the peer, upon return contains an NSError object that explains the problem.

Return Value

YES if a connection was established to the remote peer; NO if an error occurred.

Discussion

When your session acts as a server, client peers can discover your session and attempt to connect to it. When a client attempts to connect to the session, the delegate’s session:didReceiveConnectionRequestFromPeer: method is called to decide whether the peer should be connected. Your application calls this method to accept the request, or denyConnectionFromPeer: to reject it.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

cancelConnectToPeer:

Cancels a pending request to connect to another iOS device.

- (void)cancelConnectToPeer:(NSString *)peerID
Parameters
peerID

The string identifying the peer you previously requested to connect to.

Discussion

Your application previously called connectToPeer:withTimeout: to create a connection to another iOS device. When your application cancels the connection attempt, both delegates’ session:connectionWithPeerFailed:withError: methods are called.

If your application already connected to the peer, your application should call disconnectFromAllPeers instead.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

connectToPeer:withTimeout:

Creates a connection to another iOS device.

- (void)connectToPeer:(NSString *)peerID withTimeout:(NSTimeInterval)timeout
Parameters
peerID

The string that identifies the peer to connect to.

timeout

The amount of time to wait before canceling the connection attempt.

Discussion

When your application is acting as a client, it calls this method to connect to an available peer it discovered. When your application calls this method, a request is transmitted to the remote peer, who chooses whether to accept or reject the connection request.

If the connection to the remote peer is successful, the delegate’s session:peer:didChangeState: method is called for each peer it successfully connected to. If the connection fails or your application cancels the connection attempt, the session calls the delegate’s session:connectionWithPeerFailed:withError: method.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

denyConnectionFromPeer:

Called by the delegate to reject a connection request received from a remote peer.

- (void)denyConnectionFromPeer:(NSString *)peerID
Parameters
peerID

The string identifying the peer that initiated the connection to the session.

Discussion

When your session acts as a server, client peers can discover your session and attempt to connect to it. When a client attempts to connect to the session, the delegate’s session:didReceiveConnectionRequestFromPeer: method is called to decide whether the peer should be connected. Your application calls this method to reject the request or acceptConnectionFromPeer:error: to accept it.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

disconnectFromAllPeers

Disconnects the session from all connected peers.

- (void)disconnectFromAllPeers
Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

disconnectPeerFromAllPeers:

Disconnects a connected peer from all peers connected to the session.

- (void)disconnectPeerFromAllPeers:(NSString *)peerID
Parameters
peerID

A string identifying the peer to disconnect.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

displayNameForPeer:

Returns a user-readable name for a peer.

- (NSString *)displayNameForPeer:(NSString *)peerID
Parameters
peerID

A string that uniquely identifies a peer.

Return Value

The name for the peer, or nil if peerID is not associated with a visible peer.

Discussion

The display name is used to populate your user interface with the names of other peers visible to the session.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

initWithSessionID:displayName:sessionMode:

Initializes and returns a newly allocated session.

- (id)initWithSessionID:(NSString *)sessionID displayName:(NSString *)name sessionMode:(GKSessionMode)mode
Parameters
sessionID

A unique string that identifies your application. Your sessionID should be the short name of an approved Bonjour service type. If nil, the session uses the application’s bundle identifier to create a sessionID string.

name

A string identifying the user to display to other peers. If nil, the session uses the device name.

mode

The mode the session should run in. See “Session Modes” for possible values.

Return Value

An initialized session object, or nil if an error occurred.

Discussion

Only sessions running with the same sessionID are visible to your session.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

peersWithConnectionState:

Returns a list of peers in the specified connection state.

- (NSArray *)peersWithConnectionState:(GKPeerConnectionState)state
Parameters
state

The connection state to search for. See “Connection States” for possible values.

Return Value

An array of NSString objects with a peerID string for each peer visible to the session that is currently in the specified connection state. If there are no peers in the specified connection state, this method returns nil.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

sendData:toPeers:withDataMode:error:

Transmits a collection of bytes to a list of connected peers.

- (BOOL)sendData:(NSData *)data toPeers:(NSArray *)peers withDataMode:(GKSendDataMode)mode error:(NSError **)error
Parameters
data

The bytes to be sent.

peers

An array of NSString objects identifying the peers that should receive the data.

mode

The mechanism used to send the data.

error

If the data could not be queued, an NSError object describing the error.

Return Value

YES if the data was successfully queued for transmission; NO if the session object was unable to queue the data.

Discussion

The session queues the data and transmits it in the order it was queued. Data transmitted unreliably may be received out of order by the other peers.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

sendDataToAllPeers:withDataMode:error:

Transmits a collection of bytes to all connected peers.

- (BOOL)sendDataToAllPeers:(NSData *)data withDataMode:(GKSendDataMode)mode error:(NSError **)error
Parameters
data

The bytes to be sent.

mode

The mechanism used to send the data.

error

If the data could not be queued, an NSError object describing the error.

Return Value

YES if the data was successfully queued for transmission; NO if the session object was unable to queue the data.

Discussion

The session queues the data and transmits it when the network is free.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

setDataReceiveHandler:withContext:

Sets the object that handles data received from other peers connected to the session.

- (void)setDataReceiveHandler:(id)handler withContext:(void *)context
Parameters
handler

The object you want the session to call when it receives data from other peers.

context

Arbitrary data to be passed to each invocation of the handler.

Discussion

The handler must implement a method with the following signature:

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context;

where data contains the bytes received from a remote peer, peer is a string that identifies the peer, session is the session that received the data, and context is the same context that was passed into the original call to setDataReceiveHandler:withContext:.

Availability
  • Available in iOS 3.0 and later.
Declared In
GKSession.h

Constants

Data Transmission Modes

The mechanism used to transmit data to other peers.

typedef enum {
   GKSendDataReliable,
   GKSendDataUnreliable,
} GKSendDataMode;
Constants
GKSendDataReliable

The data is sent continuously until it is successfully received by the intended recipients or the connection times out.

Reliable transmissions are delivered in the order they were sent. Use this when you need to guarantee delivery.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKSendDataUnreliable

The data is sent once and is not sent again if a transmission error occurred.

Data transmitted unreliably may be received out of order by recipients. Use this for small packets of data that must arrive quickly to be useful to the recipient.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

Session Modes

Modes that determine how a session interacts with other peers.

typedef enum {
   GKSessionModeServer,
   GKSessionModeClient,
   GKSessionModePeer,
} GKSessionMode;
Constants
GKSessionModeServer

A server advertises itself to local devices using its sessionID property.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKSessionModeClient

A client searches for servers advertising the same sessionID property.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKSessionModePeer

A peer advertises like a server and searches like a client.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

Connection States

The state of a peer known to the session.

typedef enum {
   GKPeerStateAvailable,
   GKPeerStateUnavailable,
   GKPeerStateConnected,
   GKPeerStateDisconnected,
   GKPeerStateConnecting
} GKPeerConnectionState;
Constants
GKPeerStateAvailable

A peer not connected to the session, but one that the session can connect to.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKPeerStateUnavailable

A peer that is no longer interested in receiving connections.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKPeerStateConnected

A peer connected to the session.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKPeerStateDisconnected

A peer that disconnected from the session.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

GKPeerStateConnecting

A peer attempting to connect to the session.

Available in iOS 3.0 and later.

Declared in GKPublicConstants.h.

Discussion

States are not mutually exclusive. For example, a peer can be available for other peers to discover while it is attempting to connect to another peer.

The Session Error Domain

The GKSession error domain.

NSString * const GKSessionErrorDomain;
Constants
GKSessionErrorDomain

An error occurred in GKSession.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSession Errors

Error codes for the GKSession error domain.

typedef enum {
   GKSessionInvalidParameterError = 30500,
   GKSessionPeerNotFoundError = 30501,
   GKSessionDeclinedError = 30502,
   GKSessionTimedOutError = 30503,
   GKSessionCancelledError = 30504,
   GKSessionConnectionFailedError = 30505,
   GKSessionConnectionClosedError = 30506,
   GKSessionDataTooBigError = 30507,
   GKSessionNotConnectedError = 30508,
   GKSessionCannotEnableError = 30509,
   GKSessionInProgressError = 30510,
   GKSessionConnectivityError = 30201,
   GKSessionTransportError = 30202,
   GKSessionInternalError = 30203,
   GKSessionUnknownError = 30204,
   GKSessionSystemError = 30205
} GKSessionError;
Constants
GKSessionInvalidParameterError

A parameter had an unexpected value.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionPeerNotFoundError

A peer with the specified peerID string could not be found.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionDeclinedError

The peer your application tried to connect to refused the connection.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionTimedOutError

The operation could not be completed in the specified timeout period.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionCancelledError

A peer that invited the session to connect to them canceled the connection request.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionConnectionFailedError

The attempt to establish a connection with another peer failed.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionConnectionClosedError

The connection to another peer closed unexpectedly.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionDataTooBigError

The data your application attempted to send was too large for the session to transmit in a single call.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionNotConnectedError

Reserved for future use.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionCannotEnableError

Bluetooth is not currently available.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionInProgressError

The peer your application attempted to connect to has already requested a connection to your session.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionConnectivityError

An error occurred in the GKSession object's connection code.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionTransportError

An error occurred in the GKSession object's transport code.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionInternalError

An serious error occurred inside GKSession.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionUnknownError

Reserved for when the error does not fit in another category above.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.

GKSessionSystemError

An error occurred outside of the GKSession object's control, such as memory allocation.

Available in iOS 3.0 and later.

Declared in GKSessionError.h.