iOS Developer Library

Developer

MultipeerConnectivity Framework Reference MCSession Class Reference

Options
Deployment Target:

On This Page
Language:

MCSession

An MCSession object enables and manages communication among all peers in a Multipeer Connectivity session.

Initiating a Session

To set up a session, your app must do the following:

  1. Create an MCPeerID object that represents the local peer, and use it to initialize the session object.

  2. Add peers to the session using a browser object, a browser view controller, or manually. (Sessions currently support up to 8 peers, including the local peer.)

  3. Wait until the session calls your delegate object’s session:peer:didChangeState: method with MCSessionStateConnected as the new state, along with an object that tells you which peer became connected.

You should also set up an advertiser or advertiser assistant to allow other devices to ask your app to join a session that they create.

Communicating With Peers

Once you have set up the session, your app can send data to other peers by calling one of the following methods:

Managing Peers Manually

If you decide to write your own peer discovery code (with NSNetService or the Bonjour C API, for example), you can also manually connect nearby peers into a session. To do this, your app must do the following:

  1. Establish a connection to nearby peers and exchange peer IDs with those peers. Each peer should serialize its own local MCPeerID object with NSKeyedArchiver, and the receiving peer should unserialize it with NSKeyedUnarchiver.

  2. Exchange connection data. After you have obtained the nearby peer’s ID object, call nearbyConnectionDataForPeer:withCompletionHandler: to obtain a connection data object specific to that nearby peer.

    When the completion handler block is called, send the resulting connection data object to that peer.

  3. When your app receives connection data from another peer, it must call connectPeer:withNearbyConnectionData: to add that peer to the session.

You can also cancel an outstanding connection attempt by calling cancelConnectPeer:.

Disconnecting

To leave a session, your app must call disconnect.

Inheritance


Conforms To


Import Statement


Swift

import MultipeerConnectivity

Objective-C

@import MultipeerConnectivity;

Availability


Available in iOS 7.0 and later.
  • Creates a Multipeer Connectivity session.

    Declaration

    Swift

    convenience init!(peer myPeerID: MCPeerID!)

    Objective-C

    - (instancetype)initWithPeer:(MCPeerID *)myPeerID

    Parameters

    myPeerID

    A local identifier that represents the device on which your app is currently running.

    Return Value

    Returns the initialized session object, or nil if an error occurs.

    Discussion

    This method is equivalent to calling initWithPeer:securityIdentity:encryptionPreference: with a nil identity and MCEncryptionOptional as the encryption preference.

    This method throws an exception if the provided peer ID object is invalid or nil.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Creates a Multipeer Connectivity session, providing security information.

    Declaration

    Swift

    init!(peer myPeerID: MCPeerID!, securityIdentity identity: [AnyObject]!, encryptionPreference encryptionPreference: MCEncryptionPreference)

    Objective-C

    - (instancetype)initWithPeer:(MCPeerID *)myPeerID securityIdentity:(NSArray *)identity encryptionPreference:(MCEncryptionPreference)encryptionPreference

    Parameters

    myPeerID

    A local identifier that represents the device on which your app is currently running.

    identity

    An array containing information that can be used to identify the local peer to other nearby peers.

    The first object in this array should be a SecIdentityRef object that provides the local peer’s identity.

    The remainder of the array should contain zero or more additional SecCertificateRef objects that provide any intermediate certificates that nearby peers might require when verifying the local peer’s identity. These certificates should be sent in certificate chain order.

    When you add other peers to the session, those peers receive your local peer’s certificate (extracted from the provided identity) and any additional certificates that you provided. It is the receiving peer’s responsibility to validate that certificate, if desired.

    encryptionPreference

    An integer value that indicates whether encryption is required, preferred, or undesirable.

    Return Value

    Returns the initialized session object, or nil if an error occurs.

    Discussion

    This method throws an exception if the provided peer ID object is invalid or nil.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • delegate delegate Property

    The delegate object that handles session-related events.

    Declaration

    Swift

    weak var delegate: MCSessionDelegate!

    Objective-C

    @property(weak, nonatomic) id< MCSessionDelegate > delegate

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Indicates whether the connection prefers encrypted connections, unencrypted connections, or has no preference. (read-only)

    Declaration

    Swift

    var encryptionPreference: MCEncryptionPreference { get }

    Objective-C

    @property(readonly, nonatomic) MCEncryptionPreference encryptionPreference

    Discussion

    This value is set when you initialize the object, and cannot be changed later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • myPeerID myPeerID Property

    A local identifier that represents the device on which your app is currently running. (read-only)

    Declaration

    Swift

    var myPeerID: MCPeerID! { get }

    Objective-C

    @property(readonly, nonatomic) MCPeerID *myPeerID

    Discussion

    This value is set when you initialize the object, and cannot be changed later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • The security identity of the local peer. (read-only)

    Declaration

    Swift

    var securityIdentity: [AnyObject]! { get }

    Objective-C

    @property(readonly, nonatomic) NSArray *securityIdentity

    Discussion

    This value is set when you initialize the object, and cannot be changed later. For details on this value, see the documentation for initWithPeer:securityIdentity:encryptionPreference:.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Connect a peer to the session manually.

    Declaration

    Swift

    func connectPeer(_ peerID: MCPeerID!, withNearbyConnectionData data: NSData!)

    Objective-C

    - (void)connectPeer:(MCPeerID *)peerID withNearbyConnectionData:(NSData *)data

    Parameters

    peerID

    The peer ID object obtained from the nearby peer.

    data

    The connection data object obtained from the nearby peer.

    Discussion

    This method is used for connecting to peers when you are using your own service discovery code. For more information, see Managing Peers Manually.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Cancels an attempt to connect to a peer.

    Declaration

    Swift

    func cancelConnectPeer(_ peerID: MCPeerID!)

    Objective-C

    - (void)cancelConnectPeer:(MCPeerID *)peerID

    Parameters

    peerID

    The ID of the nearby peer.

    Discussion

    This method is used for canceling connections to peers when you are using your own service discovery code. It should be called in two situations:

    • If your app calls connectPeer:withNearbyConnectionData: and later decides to cancel the connection attempt

    • If your app has obtained nearby connection data for a peer and later decides not to connect to it

    For more information, see Managing Peers Manually.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • An array of all peers that are currently connected to this session. (read-only)

    Declaration

    Swift

    var connectedPeers: [AnyObject]! { get }

    Objective-C

    @property(readonly, nonatomic) NSArray *connectedPeers

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Obtains connection data for the specified peer.

    Declaration

    Swift

    func nearbyConnectionDataForPeer(_ peerID: MCPeerID!, withCompletionHandler completionHandler: ((NSData!, NSError!) -> Void)!)

    Objective-C

    - (void)nearbyConnectionDataForPeer:(MCPeerID *)peerID withCompletionHandler:(void (^)(NSData *connectionData, NSError *error))completionHandler

    Parameters

    peerID

    A peer ID object obtained from the nearby peer that you want to add to a session.

    completionHandler

    A handler that is called when connection data is available or when an error occurs.

    Discussion

    This method provides connection data that is required when adding a specific nearby peer to a session if you are using your own service discovery code. For more information, see Managing Peers Manually.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Sends a message encapsulated in an NSData object to nearby peers.

    Declaration

    Swift

    func sendData(_ data: NSData!, toPeers peerIDs: [AnyObject]!, withMode mode: MCSessionSendDataMode, error error: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)sendData:(NSData *)data toPeers:(NSArray *)peerIDs withMode:(MCSessionSendDataMode)mode error:(NSError **)error

    Parameters

    data

    An object containing the message to send.

    peerIDs

    An array of peer ID objects representing the peers that should receive the message.

    mode

    The transmission mode to use (reliable or unreliable delivery).

    error

    The address of an NSError pointer where an error object should be stored upon error.

    Return Value

    Returns YEStrue if the message was successfully enqueued for delivery, or NOfalse if an error occurred.

    Discussion

    This method is asynchronous (non-blocking).

    On the recipient device, the session object calls its delegate object’s session:didReceiveData:fromPeer: method with the message after it has been fully received.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Sends the contents of a URL to a peer.

    Declaration

    Swift

    func sendResourceAtURL(_ resourceURL: NSURL!, withName resourceName: String!, toPeer peerID: MCPeerID!, withCompletionHandler completionHandler: ((NSError!) -> Void)!) -> NSProgress!

    Objective-C

    - (NSProgress *)sendResourceAtURL:(NSURL *)resourceURL withName:(NSString *)resourceName toPeer:(MCPeerID *)peerID withCompletionHandler:(void (^)(NSError *error))completionHandler

    Parameters

    resourceURL

    A file or HTTP URL.

    resourceName

    A name for the resource.

    peerID

    The peer that should receive this resource.

    completionHandler

    A block that gets called when delivery succeeds or fails. Upon success, the handler is called with an error value of nil. Upon failure, the handle is called with an error object that indicates what went wrong.

    Return Value

    Returns an NSProgress object that can be used to query the status of the transfer or cancel the transfer.

    Discussion

    This method is asynchronous (non-blocking).

    On the local device, the completion handler block is called when delivery succeeds or when an error occurs.

    On the recipient device, the session calls its delegate’s session:didStartReceivingResourceWithName:fromPeer:withProgress: method as soon as it begins receiving the resource. This method provides an NSProgress object that your app can use to cancel the transfer or check its status.

    Upon successful delivery, on the recipient device, the session calls its delegate’s session:didFinishReceivingResourceWithName:fromPeer:atURL:withError: method. The received resource is written to a file in a temporary location with the same base name; the app is responsible for opening the file or moving it to a permanent location before that delegate method returns.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Opens a byte stream to a nearby peer.

    Declaration

    Swift

    func startStreamWithName(_ streamName: String!, toPeer peerID: MCPeerID!, error error: NSErrorPointer) -> NSOutputStream!

    Objective-C

    - (NSOutputStream *)startStreamWithName:(NSString *)streamName toPeer:(MCPeerID *)peerID error:(NSError **)error

    Parameters

    streamName

    A name for the stream. This name is provided to the nearby peer.

    peerID

    The ID of the nearby peer.

    error

    The address of an NSError pointer where an error object should be stored if something goes wrong.

    Return Value

    Returns an output stream object upon success or nil if a stream could not be established.

    Discussion

    This method is non-blocking.

    For more information about performing networking with input and output streams, read Networking Programming Topics.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Disconnects the local peer from the session.

    Declaration

    Swift

    func disconnect()

    Objective-C

    - (void)disconnect

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Indicates whether delivery of data should be guaranteed.

    Declaration

    Swift

    enum MCSessionSendDataMode : Int { case Reliable case Unreliable }

    Objective-C

    typedef NS_ENUM (NSInteger, MCSessionSendDataMode ) { MCSessionSendDataReliable, MCSessionSendDataUnreliable };

    Constants

    • Reliable

      MCSessionSendDataReliable

      The framework should guarantee delivery of each message, enqueueing and retransmitting data as needed, and ensuring in-order delivery.

      This message type should be used for application-critical data.

      Available in iOS 7.0 and later.

    • Unreliable

      MCSessionSendDataUnreliable

      Messages to peers should be sent immediately without socket-level queueing. If a message cannot be sent immediately, it should be dropped. The order of messages is not guaranteed.

      This message type should be used for data that ceases to be relevant if delayed, such as real-time gaming data.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Indicates the current state of a given peer within a session.

    Declaration

    Swift

    enum MCSessionState : Int { case NotConnected case Connecting case Connected }

    Objective-C

    typedef NS_ENUM (NSInteger, MCSessionState ) { MCSessionStateNotConnected, MCSessionStateConnecting, MCSessionStateConnected };

    Constants

    • NotConnected

      MCSessionStateNotConnected

      The peer is not (or is no longer) in this session.

      Available in iOS 7.0 and later.

    • Connecting

      MCSessionStateConnecting

      A connection to the peer is currently being established.

      Available in iOS 7.0 and later.

    • Connected

      MCSessionStateConnected

      The peer is connected to this session.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Indicates whether a session should use encryption when communicating with nearby peers.

    Declaration

    Swift

    enum MCEncryptionPreference : Int { case Optional case Required case None }

    Objective-C

    typedef NS_ENUM (NSInteger, MCEncryptionPreference ) { MCEncryptionOptional = 0, MCEncryptionRequired = 1, MCEncryptionNone = 2, };

    Constants

    • Optional

      MCEncryptionOptional

      The session prefers to use encryption, but will accept unencrypted connections.

      Available in iOS 7.0 and later.

    • Required

      MCEncryptionRequired

      The session requires encryption.

      Available in iOS 7.0 and later.

    • None

      MCEncryptionNone

      The session should not be encrypted.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • Error codes found in MCErrorDomain error domain NSError objects returned by methods in the Multipeer Connectivity framework.

    Declaration

    Swift

    enum MCErrorCode : Int { case Unknown case NotConnected case InvalidParameter case Unsupported case TimedOut case Cancelled case Unavailable }

    Objective-C

    enum MCErrorCode { MCErrorUnknown = 0, MCErrorNotConnected = 1, MCErrorInvalidParameter = 2, MCErrorUnsupported = 3, MCErrorTimedOut = 4, MCErrorCancelled = 5, MCErrorUnavailable = 6, }; typedef NSInteger MCErrorCode;

    Constants

    • Unknown

      MCErrorUnknown

      An unknown error occurred.

      Available in iOS 7.0 and later.

    • NotConnected

      MCErrorNotConnected

      Your app attempted to send data to a peer that is not connected.

      Available in iOS 7.0 and later.

    • InvalidParameter

      MCErrorInvalidParameter

      Your app passed an invalid value as a parameter.

      Available in iOS 7.0 and later.

    • Unsupported

      MCErrorUnsupported

      The operation is unsupported. For example, this error is returned if you call sendResourceAtURL:withName:toPeer:withCompletionHandler: with a URL that is neither a local file nor a web URL.

      Available in iOS 7.0 and later.

    • TimedOut

      MCErrorTimedOut

      The connection attempt timed out.

      Available in iOS 7.0 and later.

    • Cancelled

      MCErrorCancelled

      The operation was cancelled by the user.

      Available in iOS 7.0 and later.

    • Unavailable

      MCErrorUnavailable

      Multipeer connectivity is currently unavailable.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import MultipeerConnectivity;

    Swift

    import MultipeerConnectivity

    Availability

    Available in iOS 7.0 and later.

  • The error domain for errors specific to Multipeer Connectivity.

    Declaration

    Swift

    let MCErrorDomain: NSString!

    Objective-C

    NSString * const MCErrorDomain;

    Constants

    • MCErrorDomain

      MCErrorDomain

      The NSError domain constant. If the domain value for an NSError object is equal to MCErrorDomain, then the error was produced by the Multipeer Connectivity framework itself, as opposed to a lower-level framework on which it depends.

      Available in iOS 7.0 and later.

  • Constants that define the minimum and maximum number of peers supported in a session.

    Declaration

    Swift

    let kMCSessionMaximumNumberOfPeers: Int let kMCSessionMinimumNumberOfPeers: Int

    Objective-C

    NSUInteger const kMCSessionMaximumNumberOfPeers; NSUInteger const kMCSessionMinimumNumberOfPeers;

    Constants

    • kMCSessionMaximumNumberOfPeers

      kMCSessionMaximumNumberOfPeers

      The maximum number of peers that a session can support, including the local peer.

      Available in iOS 7.0 and later.

    • kMCSessionMinimumNumberOfPeers

      kMCSessionMinimumNumberOfPeers

      The minimum number of peers that a session can support, including the local peer.

      Available in iOS 7.0 and later.