Realtime Client Library API

Presence

Presence enables clients to be aware of other clients that are currently “present” on a channel. Each member present on a channel has a unique self-assigned client identifier and system-assigned connection identifier, along with an optional payload that can be used to describe the member’s status or attributes. Presence allows you to quickly build apps such as chat rooms and multiplayer games by automatically keeping track of who is present in real time across any device.

Getting started

The Presence object provides a straightforward API to subscribe to presence events such as members entering or leaving, retrieve a list of members present, or register the connected client as “present” on a channel. Here is a simple presence example using the presencePresence propertyfieldattribute of the Channel object to enter a channel and subscribe to presence events.

var realtime = new Ably.Realtime({
  key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF',
  clientId: 'bob' }
);
var channel = realtime.channels.get('law-dry-gem');
channel.presence.subscribe('enter', function(member) {
  alert('Member ' + member.clientId + ' entered');
});
channel.presence.enter();
var Ably = require('ably');
var realtime = new Ably.Realtime({
  key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF',
  clientId: 'bob' }
);
var channel = realtime.channels.get('law-dry-gem');
channel.presence.subscribe('enter', function(member) {
  alert('Member ' + member.clientId + ' entered');
});
channel.presence.enter();
realtime = Ably::Realtime.new(key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF', client_id: 'bob')
channel = realtime.channels.get('law-dry-gem')
channel.presence.subscribe(:enter) do |member|
  puts "Member #{member.client_id} entered"
end
channel.presence.enter
ClientOptions options = new ClientOptions("xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF");
options.clientId = "bob";
AblyRealtime realtime = new AblyRealtime(options);
Channel channel = realtime.channels.get("law-dry-gem");
channel.presence.subscribe(new PresenceListener() {
  @Override
  public void onPresenceMessage(PresenceMessage member) {
    System.out.println("Member " + member.clientId + " : " + member.action.toString());
  }
});
channel.presence.enter(null, new CompletionListener());
var options = new ClientOptions("xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF") { ClientId =  "bob"};
var realtime = new AblyRealtime(options);
var channel = realtime.Channels.Get("law-dry-gem");
channel.Presence.Subscribe(member => {
  Console.WriteLine("Member " + member.clientId + " : " + member.action)
});
await channel.Presence.EnterAsync(null);
ARTClientOptions *options = [[ARTClientOptions alloc] initWithKey:@"xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF"];
options.clientId = @"bob";
ARTRealtime *realtime = [[ARTRealtime alloc] initWithOptions:options];
ARTRealtimeChannel *channel = [realtime.channels get:@"law-dry-gem"];
[channel.presence subscribe:ARTPresenceEnter callback:^(ARTPresenceMessage *member) {
    NSLog(@"Member %@ entered", member.clientId);
}];
[channel.presence enter:nil];
let options = ARTClientOptions(key: "xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF")
options.clientId = "bob"
let realtime = ARTRealtime(options: options)
let channel = realtime.channels.get("law-dry-gem")
channel.presence.subscribe(.Enter) { member in
    print("Member \(member.clientId) entered")
}
channel.presence.enter(nil)

Note that all examples on this page assume you are running them within an EventMachine reactor. Find out more in our Realtime usage documentation.

If you would prefer to just dive into code and see some examples of how to use presence via the Realtime API, then we recommend you take a look at our Realtime tutorials.

Presence

In order to be present on a channel, a client must be identified by having a client ID, have permission to be present, and be attached to the channel. For simplicity, the library will implicitly attach to a channel when entering or subscribing to presence events. Clients are assigned a clientIdclient_idClientId when using token authentication, find out more about token authentication.

A single clientIdclient_idClientId may be present multiple times on the same channel via different client connections. As far as Ably is concerned, these are different members of the presence set for the channel, however they will be differentiated by their unique connectionIdConnectionIdconnection_id. For example, if a client with ID “Sarah” is connected to a chat channel on both a desktop and a mobile device simultaneously, “Sarah” will be present twice in the presence member set with the same client ID, yet will have two unique connection IDs. A member of the presence set is therefore unique by the combination of the clientIdclient_idClientId and connectionIdConnectionIdconnection_id strings.

Presence states and events

Whenever a member enters or leaves a channel, or updates their member data, a presence event is emitted to all presence subscribers on that channel. Subscribing to presence events makes it incredibly easy to build an app that shows, in real time, any changes to clients connected to Ably and present on a channel.

The following presence events are emitted:

:enterPresenceAction.ENTERAction.ENTERenter
A new member has entered the channel
:leavePresenceAction.LEAVEAction.LEAVEleave
A member who was present has now left the channel. This may be a result of an explicit request to leave or implicitly when detaching from the channel. Alternatively, if a member’s connection is abruptly disconnected and they do not resume their connection within a minute, Ably treats this as a leave event as the client is no longer present
:updatePresenceAction.UPDATEAction.UPDATEupdate
An already present member has updated their member data. Being notified of member data updates can be very useful, for example, it can be used to update the status of a user when they are typing a message
:presentPresenceAction.PRESENTAction.PRESENTpresent
When subscribing to presence events on a channel that already has members present, this event is emitted for every member already present on the channel before the subscribe listener was registered

View a presence states and events example

Member data

In addition to the clientIdclient_idClientId for members on a channel, it is also possible to include data when entering a channel. Clients can update their data at any point which will be broadcasted to all presence subscribers as an :updateAction.UPDATEupdate event.

/* Subscribe to presence enter events */
channel.presence.on('enter', function(member) {
  console.log(member.data); // => not moving
});

/* Subscribe to presence update events */
channel.presence.on('update', function(member) {
  console.log(member.data); // => travelling North
});

/* Enter this client with data and update once entered */
channel.presence.enter('not moving', function(err) {
  channel.presence.update('travelling North');
});
/* Subscribe to presence enter events */
channel.presence.on('enter', function(member) {
  console.log(member.data); // => not moving
});

/* Subscribe to presence update events */
channel.presence.on('update', function(member) {
  console.log(member.data); // => travelling North
});

/* Enter this client with data and update once entered */
channel.presence.enter('not moving', function(err) {
  channel.presence.update('travelling North');
});
/* Subscribe to presence enter and update events */
channel.presence.subscribe(new PresenceListener() {
  @Override
  public void onPresenceMessage(PresenceMessage member) {
    switch (member.action) {
      case ENTER: {
        System.out.println(member.data); // => not moving
        break;
      }
      case UPDATE: {
        System.out.println(member.data); // => travelling North
        break;
      }
    }
  }
});

/* Enter this client with data and update once entered */
channel.presence.enter("not moving", new CompletionListener() {
  @Override
  public void onSuccess() {
    channel.presence.update("travelling North", new CompletionListener());
  }
});
/* Subscribe to presence enter and update events */
channel.Presence.Subscribe(member =>
{
    switch (member.action)
    {
        case PresenceAction.Enter:
        case PresenceAction.Update:
            {
                Console.WriteLine(member.data); // => travelling North
                break;
            }
    }
});

/* Enter this client with data and update once entered */
await channel.Presence.EnterAsync("not moving");
await channel.Presence.UpdateAsync("travelling North");
# Subscribe to presence enter events
channel.presence.subscribe(:enter) do |member|
  puts member.data # => not moving
end

# Subscribe to presence update events
channel.presence.subscribe(:update) do |member|
  puts member.data # => travelling North
end

# Enter this client with data and update once entered
channel.presence.enter(data: 'not moving') do
  channel.presence.update(data: 'travelling North')
end
// Subscribe to presence enter events
[channel.presence subscribe:ARTPresenceEnter callback:^(ARTPresenceMessage *member) {
    NSLog(@"%@", member.data); // prints "not moving"
}];

// Subscribe to presence update events
[channel.presence subscribe:ARTPresenceUpdate callback:^(ARTPresenceMessage *member) {
    NSLog(@"%@", member.data); // prints "travelling North"
}];

// Enter this client with data and update once entered
[channel.presence enter:@"not moving" callback:^(ARTErrorInfo *error) {
    [channel.presence update:@"travelling North"];
}];
// Subscribe to presence enter events
channel.presence.subscribe(.Enter) { member in
    print(member.data) // prints "not moving"
}

// Subscribe to presence update events
channel.presence.subscribe(.Update) { member in
    print(member.data) // prints "travelling North"
}

// Enter this client with data and update once entered
channel.presence.enter("not moving") { error in
    channel.presence.update("travelling North")
}

Presence member list

The Presence object exposes a getGet method allowing a client to retrieve an array of all members present on the channel. The Ably client is responsible for keeping track of the presence set from the time that the channel is attached; an up to date presence set is pushed to the client following attach and the presence set is updated on each subsequent presence event. Thus getGet returns the already-known presence set retained in memory and does not trigger a new request to the Ably service.

channel.presence.get(function(err, members) {
  console.log('There are ' + members.length + ' members on this channel');
  console.log('The first member has client ID: ' + members[0].clientId);
});
channel.presence.get(function(err, members) {
  console.log('There are ' + members.length + ' members on this channel');
  console.log('The first member has client ID: ' + members[0].clientId);
});
channel.presence.get do |members|
  puts "There are #{members.size} members on this channel"
  puts "The first member has client ID: #{members.first.client_id}"
end
PresenceMessage[] members = channel.presence.get();
System.out.println("There are " + members.length + " members on this channel");
System.out.println("The first member has client ID: " + members[0].clientId);
IEnumerable<PresenceMessage> presence = await channel.Presence.GetAsync();
Console.WriteLine($"There are {presence.Count()} members on this channel");
Console.WriteLine($"The first member has client ID: {presence.First().clientId}");
[channel.presence get:^(NSArray<ARTPresenceMessage *> *members, ARTErrorInfo *error) {
    NSLog(@"There are %lu members on this channel", [members count]);
    NSLog(@"The first member has client ID: %@", members[0].clientId);
}];
channel.presence.get { members, error in
    print("There are \(members.count) members on this channel")
    print("The first member has client ID: \(members[0].clientId)")
}

Presence History

The Presence object exposes a historyHistory method allowing a client to retrieve historical presence events on the channel. Presence history can be used to return continuous presence event history up to the exact point a realtime channel was attached.

History provides access to instantaneous “live” history as well as the longer term persisted history for presence channels. If persisted history is enabled for the channel, then presence events will typically be stored for 24 – 72 hours. If persisted history is not enabled, Ably retains the last two minutes of presence event history in memory.

The following example retrieves the first two pages of historical presence events published up until the point the channel was attached.

channel.attach(function() {
  var presence = channel.presence;
  presence.history({ untilAttach: true }, function(err, resultPage) {
    if(err) {
      console.log('Unable to get presence history; err = ' + err.message);
    } else {
      console.log(resultPage.items.length + ' presence events received in first page');
      if(resultPage.hasNext()) {
        resultPage.next(function(err, nextPage) { ... });
      }
  });
});
channel.attach(function() {
  var presence = channel.presence;
  presence.history({ untilAttach: true }, function(err, resultPage) {
    if(err) {
      console.log('Unable to get presence history; err = ' + err.message);
    } else {
      console.log(resultPage.items.length + ' presence events received in first page');
      if(resultPage.hasNext()) {
        resultPage.next(function(err, nextPage) { ... });
      }
  });
});
channel.attach do
  presence = channel.presence
  presence.history(until_attach: true) do |result_page|
    puts "#{result_page.items.length} presence events received in first page"
    if result_page.has_next?
      result_page.next { |next_page| ... }
    end
  end
end
Param[] options = new Param[]{ new Param("untilAttach", "true") }
PaginatedResult<PresenceMessage> resultPage = channel.presence.history(options);
System.out.println(resultPage.items().length + " presence events received in first page");
if(resultPage.hasNext()) {
  PaginatedResult<PresenceMessage> nextPage = resultPage.next();
  System.out.println(nextPage.items().length + " presence events received in 2nd page");
}
PaginatedResult<PresenceMessage> resultPage;
resultPage = await channel.Presence.HistoryAsync(untilAttach: true);
Console.WriteLine(resultPage.Items.Count + " presence events received in first page");
if (resultPage.HasNext)
{
    PaginatedResult<PresenceMessage> nextPage = await resultPage.NextAsync();
    Console.WriteLine(nextPage.Items.Count + " presence events received in 2nd page");
}
ARTRealtimeHistoryQuery *query = [[ARTRealtimeHistoryQuery alloc] init];
query.untilAttach = YES;
[channel.presence history:query callback:^(ARTPaginatedResult<ARTPresenceMessage *> *resultPage,
                                           ARTErrorInfo *error) {
    NSLog(@"%lu presence events received in first page", [resultPage.items count]);
    if (resultPage.hasNext) {
        [resultPage next:^(ARTPaginatedResult<ARTPresenceMessage *> *nextPage, ARTErrorInfo *error) {
            NSLog(@"%lu presence events received in 2nd page", [nextPage.items count]);
        }];
    }
}];
let query = ARTRealtimeHistoryQuery()
query.untilAttach = true
channel.presence.history(query) { resultPage, error in
    let resultPage = resultPage!
    print("\(resultPage.items.count) presence events received in first page")
    if resultPage.hasNext {
        resultPage.next { nextPage, error in
            print("\(nextPage!.items.count) presence events received in 2nd page")
        }
    }
}

See the presence history documentation for further details of the supported query parameters.

Managing multiple client IDs

Each unique clientIdclient_idClientId may only be present once when entering on behalf of another client as the unique identifier for each member in a presence set is the combined clientIdclient_idClientId and shared connectionIdConnectionIdconnection_id

An Ably client instance might, if on an application server for example, publish messages and be present on channels on behalf of multiple distinct client IDs. The channel’s Presence object therefore also supports methods that enable presence messages to be emitted for a clientIdclient_idClientId specified at the time of the call, rather than implicitly based on the clientIdclient_idClientId specified when the library is instanced or authenticated.

In order to be able to publish presence changes for arbitrary client IDs, the client library must have been instanced either with an API key, or with a token bound to a wildcard client ID.

var rest = new Ably.Rest({ key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF' });
/* request a wildcard token */
rest.auth.requestToken({ clientId: '*' }, function(err, token) {
  var realtime = new Ably.Realtime({ token: token });
  var channel = realtime.channels.get('realtime-chat');

  channel.presence.subscribe('enter', function(member) {
    console.log(member.client_id + 'entered realtime-chat');
  });

  channel.presence.enterClient('Bob'); // => Bob entered realtime-chat
  channel.presence.enterClient('Mary'); // => Mary entered realtime-chat
});
var rest = new Ably.Rest({ key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF' });
/* request a wildcard token */
rest.auth.requestToken({ clientId: '*' }, function(err, token) {
  var realtime = new Ably.Realtime({ token: token });
  var channel = realtime.channels.get('realtime-chat');

  channel.presence.subscribe('enter', function(member) {
    console.log(member.client_id + 'entered realtime-chat');
  });

  channel.presence.enterClient('Bob'); // => Bob entered realtime-chat
  channel.presence.enterClient('Mary'); // => Mary entered realtime-chat
});
rest = Ably::Rest.new(key: 'xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF')
# request a wildcard token
rest.auth.requestToken(clientId: '*') do |token|
  realtime = Ably::Realtime.new(token: token)
  channel = realtime.channels.get('realtime-chat')

  channel.presence.subscribe(:enter) do |member|
    puts "#{member.client_id} entered realtime-chat"
  end

  channel.presence.enter_client 'Bob' # => Bob entered realtime-chat
  channel.presence.enter_client 'Mary' # => Mary entered realtime-chat
end
/* request a wildcard token */
AblyRest rest = new AblyRest('xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF');
TokenParams params = new TokenParams();
params.clientId = "*";
ClientOptions options = new ClientOptions();
options.tokenDetails = rest.auth.requestToken(params, null);

AblyRealtime realtime = new AblyRealtime(options);
Channel channel = realtime.channels.get("realtime-chat");

channel.presence.subscribe(new PresenceListener() {
  @Override
  public void onPresenceMessage(PresenceMessage member) {
    System.out.println(member.clientId + " entered realtime-chat");
  }
});

CompletionListener noop = new CompletionListener();
channel.presence.enterClient("Bob", noop); /* => Bob entered realtime-chat */
channel.presence.enterClient('Mary', noop); /* => Mary entered realtime-chat */
/* request a wildcard token */
AblyRest rest = new AblyRest("xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF");
TokenParams params = new TokenParams() { ClientId = "*"};
ClientOptions options = new ClientOptions();
options.TokenDetails = await rest.Auth.RequestTokenAsync(params, null);

AblyRealtime realtime = new AblyRealtime(options);
var channel = realtime.Channels.Get("realtime-chat");

channel.Presence.Subscribe(member => {
  Console.WriteLine(member.clientId + " entered realtime-chat");
});

await channel.Presence.EnterClientAsync("Bob", null); /* => Bob entered realtime-chat */
await channel.Presence.EnterClientAsync("Mary", null); /* => Mary entered realtime-chat */
ARTRest* rest = [[ARTRest alloc] initWithKey:@"xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF"];
// request a wildcard token
ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"*"];
[rest.auth requestToken:tokenParams withOptions:nil callback:^(ARTTokenDetails *tokenDetails,
                                                              NSError *error) {
    ARTRealtime *realtime = [[ARTRealtime alloc] initWithToken:tokenDetails.token];
    ARTRealtimeChannel *channel = [realtime.channels get:@"realtime-chat"];

    [channel.presence subscribe:ARTPresenceEnter callback:^(ARTPresenceMessage *member) {
        NSLog(@"%@ entered realtime-chat", member.clientId);
    }];

    [channel.presence enterClient:@"Bob" data:nil]; // prints 'Bob entered realtime-chat'
    [channel.presence enterClient:@"Mary" data:nil]; // prints 'Mary entered realtime-chat'
}];
let rest = ARTRest(key: "xVLyHw.2oaqFA:7OOJPUBzxEHgW_UF")
// request a wildcard token
rest.auth.requestToken(ARTTokenParams(clientId: "*"), withOptions: nil) { tokenDetails, error in
    let realtime = ARTRealtime(token: tokenDetails!.token)
    let channel = realtime.channels.get("realtime-chat")

    channel.presence.subscribe(.Enter) { member in
        print("\(member.clientId) entered realtime-chat")
    }

    channel.presence.enterClient("Bob", data: nil) // prints 'Bob entered realtime-chat'
    channel.presence.enterClient("Mary", data: nil) // prints 'Mary entered realtime-chat'
}

Handling transient channel/connection failures

Any time a channel is re-attached and the presence set is re-synced, the client will check whether any members it has entered into the presence set are there. If not, it will automatically re-enter them. This means that if a channel loses continuity (for example, because a client was disconnected from Ably for more than two minutes before reconnecting), then after the channel automatically re-attaches, any presence members it had previously entered will be restored.

API Reference

Presence PropertiesARTPresence PropertiesAbly::Realtime::Presence Attributesio.ably.lib.realtime.Presence MembersIO.Ably.Realtime.Presence Properties

The Presence object exposes the following public propertiesattributesmembers:

syncCompletesync_complete?SyncComplete

A boolean field indicating whether the presence member set is synchronized with server after a channel attach.
When a channel is attached, the Ably service immediately synchronizes the presence member set with the client. Typically this process completes in milliseconds, however when the presence member set is very large, bandwidth constraints may slow this synchronization process down.

Methods

enterEnterAsync

In order to enter and be present on a channel, the client must be identified by having a client ID, have permission to be present, and be attached to the channel. For simplicity, the library will implicitly attach to a channel when entering. Entering when already entered is treated as an update.

There are two overloaded versions of this method.
With both versions, a callbackblockcompletion listener can optionally be passed in to be notified of success or failure to enter.

enter(callback(ErrorInfo err))Deferrable enter() → yieldsvoid enter(CompletionListener listener)enter(data: nil, callback: ((ARTErrorInfo?) → Void)?)Task EnterAsync()

Enter a presence channel without any data. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

enter(Object data, callback(ErrorInfo err))Deferrable enter(Object data) → yieldsvoid enter(Object data, CompletionListener listener)enter(data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task EnterAsync(object clientData)

Enter a presence channel and provide data that is associated with the current present member. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

data
data payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are strings, plain object convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully entering the channel
callback
called upon successfully entering the channel, or with an error

Callback result

On successfully entering the channel, err is null. On failure to enter, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully entering the channel, the onSuccess method of the CompletionListener is called. On failure to enter, the onError method is called with an ErrorInfo argument describing the failure reason.

Task result

On successfully entering the channel, the method will complete. On failure to enter, an AblyException will be thrown with an ErrorInfo object describing the failure reason.

Returns

A Deferrable object is returned from the method.

On successfully entering the channel, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to enter, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

leaveLeave

In order to leave the presence set of a channel, the client must have already entered and been present.

There are two overloaded versions of this method.
With both versions, a callbackblockcompletion listener can optionally be passed in to be notified of success or failure to leave.

leave(callback(ErrorInfo err))Deferrable leave() → yieldsvoid leave(CompletionListener listener)leave(data: nil, callback: ((ARTErrorInfo?) → Void)?)Task LeaveAsync()

Leave a presence channel without emitting any data.

leave(Object data, callback(ErrorInfo err))Deferrable leave(Object data) → yieldsvoid leave(Object data, CompletionListener listener)leave(data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task LeaveAsync(object clientData)

Leave a presence channel and emit data that is associated with the current leaving member.

Parameters

data
data payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are strings, plain objects convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully leaving the channel
callback
called upon leaving the channel, or with an error

Callback result

On successfully leaving the channel, err is null. On failure to leave, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully leaving the channel, the onSuccess method of the CompletionListener is called. On failure to leave, the onError method is called with an ErrorInfo argument describing the failure reason.

Task result

On successfully leaving the channel, the method will complete. On failure to leave, an AblyException will be thrown with an ErrorInfo object describing the failure reason.

Returns

A Deferrable object is returned from the method.

On successfully leaving the channel, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to leave, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

updateUpdate

Clients can update their member data on the channel which will trigger a broadcast of this update to all presence subscribers. The pre-requisites for updateUpdate are the same as for enterEnter. If an attempt to updateUpdate is made before the client has entered the channel, the update is treated as an enterEnter.


A callbackblockcompletion listener can optionally be passed in to be notified of success or failure to update the member data.

update(Object data, callback(ErrorInfo err))Deferrable update(Object data) → yieldsvoid update(Object data, CompletionListener listener)update(data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task UpdateAsync(object clientData)

Update the current member’s data and broadcast an update event to all subscribers. data may be null. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling update will implicitly attach the channel.

Parameters

data
data payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are strings, plain objects convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the current present member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully updating the member data
callback
called upon updating the channel, or with an error

Callback result

On successfully updating the data, err is null. On failure to update, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully updating the data, the onSuccess method of the CompletionListener is called. On failure to update, the onError method is called with an ErrorInfo argument describing the failure reason.

Task result

On successfully entering the channel, the method will complete. On failure to enter, an AblyException will be thrown with an ErrorInfo object describing the failure reason. The methods needs to be awaited otherwise the exception won’t be thrown.

Returns

A Deferrable object is returned from the method.

On successfully updating the data, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to update, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

getGet

Get the current presence member set for this channel. Typically, this method returns the member set immediately as the member set is retained in memory by the client. However, by default this method will wait until the presence member set is synchronized, so if the synchronization is not yet complete following a channel being attached, this method will wait until the presence member set is synchronized.

When a channel is attached, the Ably service immediately synchronizes the presence member set with the client. Typically this process completes in milliseconds, however when the presence member set is very large, bandwidth constraints may slow this synchronization process down.

When a channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling get will implicitly attach the channel.

get(Object options, callback(ErrorInfo err, PresenceMessage[] members))Deferrable get(Hash options) → yields PresenceMessage[]PresenceMessage[] get(Param[] options)get(query: ARTRealtimePresenceQuery, callback: (ARTPresenceMessage, ARTErrorInfo?) → Void)Task<IEnumerable> GetAsync(GetOptions { bool waitForSync = true, string clientId = "", string connectionId = "" })

Gets an array of members present on the channel as PresenceMessage objects.

Parameters

optionsqueryParam[] optionsoptions
an optional object containing query parametersan optional set of symbol key and value pairs containing the query parametersan optional set of parameters as specified below.
callback
is a function of the form: function(err, "PresenceMessage[]":#presence-message members)
&block
yields a PresenceMessage[] array
callback
called with a [ARTPresenceMessage], or with an error

options parametersARTRealtimePresenceQuery propertiesGetOptions properties

clientId:client_id
when provided, will filter array of members returned that match the provided clientIdclient_idClientId string
connectionId:connection_id
when provided, will filter array of members returned that match the provided connectionIdConnectionIdconnection_id":/realtime/connection/#id string
waitForSync:wait_for_sync
true A boolean value that by default waits for the initial presence synchronization following channel attachment to complete before returning the members present. When false, the current list of members is returned without waiting for a complete synchronization

Callback result

On success, members contains an array of PresenceMessage objects corresponding to the current set of present members on the channel.

On failure to retrieve the current presence member set, err contains an ErrorInfo object with the failure reason.

Returns

On success, the returned array of PresenceMessage objects corresponds to the current set of present members on the channel.

Failure to retrieve the current presence member set will raise an AblyException

Returns

On success, the returned enumerable of #PresenceMessage@ objects correspond to the current set of present members on the channel.

Failure to retrieve the current presence member set will raise an AblyException

Returns

A Deferrable object is returned from the method.

On success, the registered success blocks for the Deferrable and any block provided to the method yield an array of PresenceMessage objects to the current set of present members on the channel.

Failure to retrieve the current presence member set will trigger the errback callbacks of the Deferrable with an ErrorInfo object with the failure reason.

historyHistory

history(Object options, callback(ErrorInfo err, PaginatedResult<PresenceMessage> resultPage))Deferrable history(Hash options) → yields PaginatedResult<PresenceMessage>PaginatedResult<PresenceMessage> history(Param[] options)history(query: ARTRealtimeHistoryQuery?, callback: (ARTPaginatedResult<ARTPresenceMessage>?, ARTErrorInfo?) → Void) throwsTask<PaginatedResult> HistoryAsync(HistoryRequestParams query, bool untilAttach = false)

Gets a paginated set of historical presence message events for this channel. If the channel is configured to persist messages to disk, then the presence message event history will typically be available for 24 – 72 hours. If not, presence message events are only retained in memory by the Ably service for two minutes.

Parameters

optionsqueryParam[] optionsHistoryRequestParams query
an optional object containing query parametersan optional set of key value pairs containing query parameters, as specified in the presence history API documentation.
callback
is a function of the form: function(err, resultPage)
&block
yields a PaginatedResult<Message> array
callback
called with a ARTPaginatedResult<ARTPresenceMessage> object or an error

Further details of the supported options params, see presence history API documentation.

Callback result

On success, resultPage contains a PaginatedResult encapsulating an array of PresenceMessage objects corresponding to the current page of results. PaginatedResult supports pagination using next() and first() methods.

On failure to retrieve message history, err contains an ErrorInfo object with the failure reason.

Returns

On success, the returned PaginatedResult encapsulates an array of PresenceMessage objects corresponding to the current page of results. PaginatedResult supports pagination using next and first methods.

Failure to retrieve the message history will raise an AblyException

Returns

Returns a task that needs to be awaited.

On success, the returned PaginatedResult encapsulates an array of PresenceMessage objects corresponding to the current page of results. PaginatedResult supports pagination using NextAsync and FirstAsync methods.

Failure to retrieve the message history will raise an AblyException. Only if the task is awaited.

Returns

A Deferrable object is returned from the method.

On success, the registered success blocks for the Deferrable and any block provided to the method yield a PaginatedResult that encapsulates an array of PresenceMessage objects corresponding to the current page of results. PaginatedResult supports pagination using next() and first() methods.

Failure to retrieve the message history will trigger the errback callbacks of the Deferrable with an ErrorInfo object with the failure reason.

subscribeSubscribe

There are overloaded versions of this method:

subscribe(listener(PresenceMessage))void subscribe(PresenceListener listener)subscribe → yields PresenceMessagesubscribe(callback: (ARTPresenceMessage) → Void) → ARTEventListenervoid Subscribe(Action handler)

Subscribe to presence message events on this channel. The caller supplies a listener functionan implementation of the PresenceListener interfacea blocka handler, which is called each time one or more presence events occurs such as a member entering or leaving a channel.

subscribe(String action, listener(PresenceMessage))void subscribe(PresenceMessage.Action action, PresenceListener listener)subscribe(PresenceMessage::ACTION action) → yields PresenceMessagesubscribe(action: ARTPresenceAction, callback: (ARTPresenceMessage) → Void) → ARTEventListenervoid Subscribe(PresenceAction action, Action handler)

Subscribe to presence message events with a given action on this channel. The caller supplies a listener functionan implementation of the PresenceListener interfacea blocka handler, which is called each time one or more presence events occurs such as a member entering or leaving a channel.

subscribe(String[] actions, listener(PresenceMessage))void subscribe(PresenceMessage.Action[] actions, PresenceListener listener)subscribe(PresenceMessage::ACTION *actions) → yields PresenceMessage

Subscribe a single listener to messages on this channel for multiple name values.

Parameters

action
The presence action event to subscribe to
Type: StringPresenceMessage.ActionPresenceActionPresenceMessage::ACTION actionARTPresenceAction
actions
An argument array of action events to subscribe to
Type: String[]@*argument
listener
is a function of the form function(message) to be called for each matching presence message event
listener
Message listener to be notified for matching presence message event
Type: @PresenceListener
&block
yields matching presence message event when received on the channel
callback
called with each matching presence message when received on the channel
handler
called with each matching presence message when received on the channel

Considerations

  • If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling subscribe will implicitly attach the channel. However, regardless of the implicit attach outcome, the listenerblockhandler will still be registered
  • If subscribe is called more than once with the same listenerblockhandler, then duplicates will be registered. For example, if you subscribe twice with the same listenerblockhandler and a presence message is later received, the same listenerblockhandler will be invoked twice
  • The registered listenerblockhandler remains active on the presence channel regardless of the underlying channel state. For example, if you call subscribe when the underlying channel is attached and it later becomes detached or even failed, when the channel is reattached and a presence message is received, the listenersblockshandlers originally registered will still be invoked. Listeners are only removed when calling unsubscribe or when the underlying channel is released using the Realtime.channels.release(name)Realtime.Channels.Release(name) method
unsubscribeUnsubscribe

There are sixthree overloaded versions of this method:

unsubscribe(String action, listener)void unsubscribe(PresenceMessage.Action action, PresenceListener listener)unsubscribe(PresenceMessage::ACTION action, &listener_proc)unsubscribe(action: ARTPresenceAction, listener: ARTEventListener)bool Unsubscribe(PresenceAction presenceAction, Action handler)

Unsubscribe the given listener from presence message events on this channel for the given action. This removes an earlier event-specific subscription.

unsubscribe(listener)void unsubscribe(PresenceListener listener)unsubscribe(&listener_proc)unsubscribe(listener: ARTEventListener)bool Unsubscribe(Action handler)

Unsubscribe the given listener from presence message events on this channel. This removes an earlier subscription.

unsubscribe(String[] actions, listener)

Unsubscribe the given listener from all presence actions in the array.

unsubscribe(String action)

Unsubscribe all listeners for a given action.

unsubscribe(String[] actions)

Unsubscribe all listeners for all presence actions in the array.

unsubscribe()void unsubscribe()unsubscribe()bool Unsubscribe()

Unsubscribes all listeners to presence message events on this channel. This removes all earlier subscriptions.

Parameters

action
The presence action event to unsubscribe from
Type: StringPresenceMessage.ActionPresenceMessage::ACTION actionARTPresenceAction
actions
An array of actions to unsubscribe from
Type: String[]
listener
is the callback listener function that was previously subscribed
listener
previously registered listener
Type: @PresenceListener
handler
previously registered handler
&listener_block
previously registered listener block
listener
previous return value from a subscribe call
enterCliententer_clientEnterClientAsync

Enter this presence channel for the given clientIdclient_idClientId. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. In order to be able to publish presence changes for arbitrary client IDs, the client library must have been instanced either with an API key, or with a token bound to a wildcard client ID.

There are two overloaded versions of this method.

With both versions, a callbackblockcompletion listener can optionally be passed in to be notified of success or failure to enter.

enterClient(String clientId, callback(ErrorInfo err))Deferrable enter_client(String client_id) → yieldsvoid enterClient(String clientId, CompletionListener listener)enterClient(clientId: String, data: nil, callback: ((ARTErrorInfo?) → Void)?)Task EnterClientAsync(string clientId, object clientData)

Enter a presence channel on behalf of the provided clientIdclient_idClientId without any data. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

enterClient(String clientId, Object data, callback(ErrorInfo err))Deferrable enter_client(String client_id, Object data) → yieldsvoid enterClient(String clientId, Object data, CompletionListener listener)enterClient(clientId: String, data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task EnterClientAsync(string clientId, object clientData)

Enter a presence channel and provide data that is associated with the current present member. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

data
data payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are strings, plain object convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully entering the channel
callback
called upon successfully entering the channel, or with an error

Callback result

On successfully entering the channel, err is null. On failure to enter, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully entering the channel, the onSuccess method of the CompletionListener is called. On failure to enter, the onError method is called with an ErrorInfo argument describing the failure reason.

Returns

The method returns a Task that will need to be awaited. On success the method will complete and will not throw an exception. On failure to enter the method will throw an AblyException with an ErrorInfo argument describing the failure reason.

Returns

A Deferrable object is returned from the method.

On successfully entering the channel, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to enter, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

leaveClientleave_clientLeaveClientAsync

Leave this presence channel for the given clientIdclient_idClientId. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. In order to leave the presence set of a channel, the client must have already entered and been present.

There are two overloaded versions of this method.

With both versions, a callbackblockcompletion listenerhandler can optionally be passed in to be notified of success or failure to leave.

leaveClient(String clientId, callback(ErrorInfo err))Deferrable leave_client(String client_id) → yieldsvoid leaveClient(String clientId, CompletionListener listener)leaveClient(clientId: String, data: nil, callback: ((ARTErrorInfo?) → Void)?)Task LeaveClientAsync(string clientId, object data)

Leave a presence channel on behalf of the provided clientIdclient_idClientId without emitting any data.

leaveClient(String clientId, Object data, callback(ErrorInfo err))Deferrable leave_client(String client_id, Object data) → yieldsvoid leaveClient(String clientId, Object data, CompletionListener listener)leave(clientId: String, data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task LeaveClientAsync(string clientId, object data)

Leave a presence channel on behalf of the provided clientIdclient_idClientId and emit data that is associated with the current leaving member.

Parameters

data
data payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are strings, plain object convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully entering the channel
callback
called upon successfully entering the channel, or with an error

Callback result

On successfully leaving the channel, err is null. On failure to leave, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully leaving the channel, the onSuccess method of the CompletionListener is called. On failure to leave, the onError method is called with an ErrorInfo argument describing the failure reason.

Returns

The method returns a Task that will need to be awaited. On success the method will complete and will not throw an exception. On failure to leave the method will throw an AblyException with an ErrorInfo argument describing the failure reason.

Returns

A Deferrable object is returned from the method.

On successfully leaving the channel, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to leave, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

updateClientupdate_clientUpdateClientAsync

Clients can update the member data on behalf of the given clientIdclient_idClientId which will trigger a broadcast of this update to all presence subscribers. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. If an attempt to update is made before the member has entered the channel, the update is treated as an enter.


A callbackblockcompletion listener can optionally be passed in to be notified of success or failure to update the member data.

updateClient(String clientId, Object data, callback(ErrorInfo err))Deferrable update_client(String client_id, Object data) → yieldsvoid updateClient(String clientId, Object data, CompletionListener listener)update(clientId: String, data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Task UpdateClientAsync(string clientId, object data)

Update the member data on behalf of the provided clientIdclient_idClientId and broadcast an update event to all subscribers. data may be null. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

data
data payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are strings, plain object convertible to json, binary data as byte arrays, and null.
Type: Object
data
data payload for the member. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
&block
yields upon successfully entering the channel
callback
called upon successfully entering the channel, or with an error

Callback result

On successfully updating the data, err is null. On failure to update, err contains an ErrorInfo object describing the failure reason.

Listener result

On successfully updating the data, the onSuccess method of the CompletionListener is called. On failure to update, the onError method is called with an ErrorInfo argument describing the failure reason.

Returns

The method returns a Task that will need to be awaited. On success the method will complete and will not throw an exception. On failure to update the method will throw an AblyException with an ErrorInfo argument describing the failure reason.

Returns

A Deferrable object is returned from the method.

On successfully updating the data, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to update, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.

PresenceMessageARTPresenceMessageAbly::Models::PresenceMessageio.ably.lib.types.PresenceMessageIO.Ably.PresenceMessage

A PresenceMessage represents an individual presence update that is sent to or received from Ably.

PropertiesMembersAttributes

action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
Action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: enum { Absent, Present, Enter, Leave, Update }
action
the event signified by a PresenceMessage. See Presence action
Type: int enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
action
the event signified by a PresenceMessage. See PresenceAction
Type: int enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
action
the event signified by a PresenceMessage. See PresenceMessage::ACTION
Type: enum { :absent, :present, :enter, :leave, :update }
action
the event signified by a PresenceMessage. See PresenceMessage::ACTION
Type: const PresenceMessage::ABSENT,PRESENT,ENTER,LEAVE,UPDATE
action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: ARTPresenceAction
data
The presence update payload, if provided
Type: String, ByteArray, JSONObject, JSONArray
Data
The presence update payload, if provided
Type: String, byte[], plain C# object that can be converted to Json
data
The presence update payload, if provided
Type: String, StringBuffer, JSON Object
data
The presence update payload, if provided
Type: String, Binary (ASCII-8BIT String), Hash, Array
data
The presence update payload, if provided
Type: String, Bytearray, Dict, List
data
The message payload, if provided
Type: String, NSData, Dictionary, Array
data
The message payload, if provided
Type: NSString *, NSData *, NSDictionary *, NSArray *
data
The message payload, if provided
Type: String, Binary String, Associative Array, Array
idId
Unique ID assigned by Ably to this presence update
Type: String
clientIdclient_idClientId
The client ID of the publisher of this presence update
Type: String
connectionIdconnection_idConnectionId
The connection ID of the publisher of this presence update
Type: String
timestampTimestamp
Timestamp when the presence update was received by Ably, as milliseconds since the epoch.
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
encodingEncoding
This will typically be empty as all presence updates received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload
Type: String

Presence actionARTPresenceActionio.ably.lib.types.PresenceMessage.ActionAbly::Models::PresenceMessage::ACTIONIO.Ably.PresenceAction

Presence action is a String with a value matching any of the Realtime Presence states & events.

var PresenceActions = [
  'absent', // (reserved for internal use)
  'present',
  'enter',
  'leave',
  'update'
]

io.ably.lib.types.PresenceMessage.Action is an enum representing all the Realtime Presence states & events.

public enum Action {
  ABSENT,  // 0 (reserved for internal use)
  PRESENT, // 1
  ENTER,   // 2
  LEAVE,   // 3
  UPDATE   // 4
}

IO.Ably.PresenceAction is an enum representing all the Realtime Presence states & events.

public enum Action {
  Absent,  // 0 (reserved for internal use)
  Present, // 1
  Enter,   // 2
  Leave,   // 3
  Update   // 4
}

PresenceAction is an enum-like class representing all the Realtime Presence states & events.

class PresenceAction(object):
  ABSENT = 0    # (reserved for internal use)
  PRESENT = 1
  ENTER = 2
  LEAVE = 3
  UPDATE = 4

PresenceMessage Action is one of the class constants representing all the Realtime Presence states & events.

namespace Ably\Models;
class PresenceMessages {
  const ABSENT  = 0; /* (reserved for internal use) */
  const PRESENT = 1;
  const ENTER   = 2;
  const LEAVE   = 3;
  const UPDATE  = 4;
}

Example usage

if ($presenceMessage->action == Ably\Models\PresenceMesage::ENTER) {
  /* do something */
}

Ably::Models::PresenceMessage::ACTION is an enum-like value representing all the Realtime Presence states & events. ACTION can be represented interchangeably as either symbols or constants.

Symbol states

:absent  # => 0 (reserved for internal use)
:present # => 1
:enter   # => 2
:leave   # => 3
:update  # => 4

Constant states

PresenceMessage::ACTION.Absent  # => 0 (internal use)
PresenceMessage::ACTION.Present # => 1
PresenceMessage::ACTION.Enter   # => 2
PresenceMessage::ACTION.Leave   # => 3
PresenceMessage::ACTION.Update  # => 4

Example usage

# Example with symbols
presence.on(:attached) { ... }

# Example with constants
presence.on(Ably::Models::PresenceMessage::ACTION.Enter) { ... }

# Interchangeable
Ably::Models::PresenceMessage::ACTION.Enter == :enter # => true

ARTPresenceAction is an enum representing all the Realtime Presence states & events.

typedef NS_ENUM(NSUInteger, ARTPresenceAction) {
    ARTPresenceAbsent,
    ARTPresencePresent,
    ARTPresenceEnter,
    ARTPresenceLeave,
    ARTPresenceUpdate,
    ARTPresenceLast
};
enum ARTPresenceAction : UInt {
  case Absent
  case Present
  case Enter
  case Leave
  case Update
  case Last
}

PresenceMessage.fromEncoded

PresenceMessage.fromEncoded(Object encodedPresMsg, ChannelOptions channelOptions?) → PresenceMessage

A static factory method to create a PresenceMessage from a deserialized PresenceMessage-like object encoded using Ably’s wire protocol.

Parameters

encodedPresMsg
a PresenceMessage-like deserialized object.
Type: Object
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

A PresenceMessage object

PresenceMessage.fromEncodedArray

PresenceMessage.fromEncodedArray(Object[] encodedPresMsgs, ChannelOptions channelOptions?) → PresenceMessage[]

A static factory method to create an array of PresenceMessages from an array of deserialized PresenceMessage-like object encoded using Ably’s wire protocol.

Parameters

encodedPresMsgs
an array of PresenceMessage-like deserialized objects.
Type: Array
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

An Array of PresenceMessage objects

HistoryRequestParams

HistoryRequestParams is a type that encapsulates the parameters for a history queries. For example usage see Channel#historyChannel#History.

Members

Start
null The start of the queried interval
Type: DateTimeOffset
End
null The end of the queried interval
Type: DateTimeOffset
Limit
null By default it is null. Limits the number of items returned by history or stats
Type: Integer
Direction
Backwards Enum which is either Forwards or Backwards
Type: Direction enum
ExtraParameters
Optionally any extra query parameters that may be passed to the query. This is mainly used internally by the library to manage paging.
Type: Dictionary<string, string>

io.ably.lib.realtime.CompletionListener

A io.ably.lib.realtime.CompletionListener is an interface allowing a client to be notified of the outcome of an asynchronous operation.

public interface CompletionListener {
  // Called when the associated operation completes successfully,
  public void onSuccess();

  // Called when the associated operation completes with an error.
  public void onError(ErrorInfo reason);
}

PaginatedResultARTPaginatedResultAbly::Models::PaginatedResultio.ably.lib.types.PaginatedResultIO.Ably.PaginatedResult

A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.

PropertiesMembersAttributes

itemsItems
contains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)
Type: Array <Message, Presence, Stats>Type: List <Message, Presence, Stats>

Methods

firstFirst

first(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult firstPaginatedResult first()PaginatedResult first()Task<PaginatedResult> FirstAsync()PaginatedResult first()first(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)

Returns a new PaginatedResult for the first page of results. When using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.The method is asynchronous and returns a Task which needs to be awaited to get the PaginatedResult.

hasNextHasNexthas_next?has_next

Boolean hasNext()Boolean has_next?Boolean hasNext()Boolean has_next()Boolean HasNext()Boolean hasNext()Boolean hasNext()

Returns true if there are more pages available by calling nextNext and returns false if this page is the last page available.

isLastIsLastlast?is_last

Boolean isLast()Boolean last?Boolean isLast()Boolean is_last()Boolean IsLast()Boolean isLast()Boolean isLast()

Returns true if this page is the last page and returns false if there are more pages available by calling nextNext available.

nextNext

next(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult nextPaginatedResult next()PaginatedResult next()Task<PaginatedResult> NextAsync()PaginatedResult next()next(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)

Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then nulla blank PaginatedResult will be returnedNullNonenil is returned. The method is asynchronous and return a Task which needs to be awaited to get the PaginatedResultWhen using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.

Example

channel.history(function(err, paginatedResult) {
  console.log('Page 0 item 0:' + paginatedResult.items[0].data);
  paginatedResult.next(function(err, nextPage) {
    console.log('Page 1 item 1: ' + nextPage.items[1].data);
    console.log('Last page?: ' + nextPage.isLast());
  });
});
channel.history(function(err, paginatedResult) {
  console.log('Page 0 item 0:' + paginatedResult.items[0].data);
  paginatedResult.next(function(err, nextPage) {
    console.log('Page 1 item 1: ' + nextPage.items[1].data);
    console.log('Last page?: ' + nextPage.isLast());
  });
});
PaginatedResult firstPage = channel.history();
System.out.println("Page 0 item 0:" + firstPage.items[0].data);
if (firstPage.hasNext) {
  PaginatedResult nextPage = firstPage.next();
  System.out.println("Page 1 item 1:" + nextPage.items[1].data);
  System.out.println("More pages?:" + Strong.valueOf(nextPage.hasNext()));
};
PaginatedResult<Message> firstPage = await channel.HistoryAsync(null);
Message firstMessage = firstPage.Items[0];
Console.WriteLine("Page 0 item 0: " + firstMessage.data);
if (firstPage.HasNext)
{
    var nextPage = await firstPage.NextAsync();
    Console.WriteLine("Page 1 item 1:" + nextPage.Items[1].data);
    Console.WriteLine("More pages?: " + nextPage.HasNext());
}
# When using the REST sync library
first_page = channel.history
puts "Page 0 item 0: #{first_page.items[0].data}"
if first_page.has_next?
  next_page = first_page.next
  puts "Page 1 item 1: #{next_page.items[1].data}"
  puts "Last page?: #{next_page.is_last?}"
end

# When using the Realtime EventMachine library
channel.history do |first_page|
  puts "Page 0 item 0: #{first_page.items[0].data}"
  if first_page.has_next?
    first_page.next do |next_page|
      puts "Page 1 item 1: #{next_page.items[1].data}"
      puts "Last page?: #{next_page.is_last?}"
    end
  end
end
result_page = channel.history()
print 'Page 0 item 0: ' + str(result_page.items[0].data)
if result_page.has_next():
  next_page = result_page.next()
  print 'Page 1 item 1: ' + str(next_page.items[1].data)
  print 'Last page?: ' + str(next_page.is_last())
$firstPage = $channel.history();
echo("Page 0 item 0: " . $firstPage->items[0]->data);
if ($firstPage->hasNext()) {
  $nextPage = $firstPage->next();
  echo("Page 1 item 1: " . $nextPage->items[1]->data);
  echo("Last page?: " . $nextPage->isLast());
}
[channel history:^(ARTPaginatedResult<ARTMessage *> *paginatedResult, ARTErrorInfo *error) {
    NSLog(@"Page 0 item 0: %@", paginatedResult.items[0].data);
    [paginatedResult next:^(ARTPaginatedResult<ARTMessage *> *nextPage, ARTErrorInfo *error) {
        NSLog(@"Page 1 item 1: %@", nextPage.items[1].data);
        NSLog(@"Last page?: %d", nextPage.isLast());
    }];
}];
channel.history { paginatedResult, error in
    let paginatedResult = paginatedResult!
    print("Page 0 item 0: \((paginatedResult.items[0] as! ARTMessage).data)")
    paginatedResult.next { nextPage, error in
        let nextPage = nextPage!
        print("Page 0 item 0: \((nextPage.items[1] as! ARTMessage).data)")
        print("Last page? \(nextPage.isLast())")
    }
}

io.ably.lib.types.Param

Param is a type encapsulating a key/value pair. This type is used frequently in method parameters allowing key/value pairs to be used more flexible, see Channel#history for an example.

Please note that key and value attributes are always strings. If an Integer or other value type is expected, then you must coerce that type into a String.

Members

key
The key value
Type: String
value
The value associated with the key
Type: String

io.ably.lib.realtime.PresenceListener

A io.ably.lib.realtime.Presence.PresenceListener is an interface allowing a client to be notified when presence message events are received on a presence channel using a presence subscription.

public interface PresenceListener {
  // Called when one or more presence messages are received
  public void onPresenceMessage(PresenceMessage message);
}

Get started now with our free plan

It includes 100 peak connections, 3 million messages per month, and loads of features.

Create your free account