GroupSessionMessenger
An object that transfers app-specific data between the devices joined in a group session.
Declaration
final class GroupSessionMessengerMentioned in
Overview
Use a GroupSessionMessenger object to coordinate your app’s behavior across the devices attached to a group session. This object leverages the existing FaceTime communication channel to send app-specific data related to a SharePlay experience. For example, a movie-watching app might share user comments or tags while the movie plays.
You create a GroupSessionMessenger object directly and use it to send and receive app data. Create the messenger using an active GroupSession object, which manages the underlying communication channel. Store a strong reference to your GroupSessionMessenger object for the lifetime of the session. The following example shows a custom object for managing a movie-watching experience. The object stores the GroupSession object associated with the experience and creates a GroupSessionMessenger for sending messages between participants.
class CowatchingExperience : ObservableObject {
let groupSession: GroupSession<Trailer>
let messenger: GroupSessionMessenger
init(groupSession: GroupSession<Trailer>, item: Trailer) {
self.groupSession = groupSession
self.messenger = GroupSessionMessenger(session: groupSession)
self.groupSession.join()
// …
}
}For more information about establishing a group session, see GroupSession.
Receive Messages from Other Devices
The system delivers messages to your app asynchronously when they arrive and adds them to a message sequence. Use the messages(of:) or messages(of:) method to retrieve the sequence you want and iterate over its results. Use a for-in loop with the await keyword to iterate asynchronously over the results. The following example shows how a Tic Tac Toe game might retrieve moves sent by the current opponent. After receiving each move, the code adds that move to the current participant’s board.
let sessionMessenger = GroupSessionMessenger(session: groupSession)
async {
for await move in sessionMessenger.messages(of: TicTacToe.Move.self) {
self.board.addMove(move)
}
}