Skip to content

Commit

Permalink
Added swift texts and samples for connection, rooms, messages, histor…
Browse files Browse the repository at this point in the history
…y, presence, occupancy, reactions and typings.
  • Loading branch information
maratal committed Nov 28, 2024
1 parent f7ca60d commit 0761952
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 17 deletions.
37 changes: 37 additions & 0 deletions content/chat/connect.textile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ product: chat
languages:
- javascript
- react
- swift
---

When you "instantiate":/chat/setup#instantiate a client, a realtime connection is established and maintained with Ably. You can interact with the connection using the @ChatClient.connection@ object in order to monitor a client's connection status.
Expand All @@ -24,6 +25,9 @@ A connection can have any of the following statuses:
blang[javascript].
Use the "@current@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.ConnectionStatus.html#current property to check which status a connection is currently in:

blang[swift].
Use the "@status@":https://sdk.ably.com/builds/ably/#status property to check which status a connection is currently in:

blang[react].
Use the "@currentStatus@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_react.UseChatConnectionResponse.html#currentStatus property returned in the response of the "@useChatConnection@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat_react.useChatConnection.html hook to check which status a connection is currently in:

Expand All @@ -44,6 +48,10 @@ const MyComponent = () => {
};
```

```[swift]
let status = await chatClient.connection.status
```

blang[react].
Hooks related to chat features, such as @useMessages@ and @useTyping@, also return the current @connectionStatus@ in their response.

Expand All @@ -63,12 +71,17 @@ blang[react].

blang[javascript].

blang[swift].

blang[javascript].
Use the "@connection.status.onChange()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.ConnectionStatus.html#onChange method to register a listener for status change updates:

blang[react].
Listeners can also be registered to monitor the changes in connection status. Any hooks that take an optional listener to monitor their events, such as typing indicator events in the @useTyping@ hook, can also register a status change listener. Changing the value provided for a listener will cause the previously registered listener instance to stop receiving events. All messages will be received by exactly one listener.

blang[swift].
Use the "@connection.onStatusChange(bufferingPolicy: .unbounded)@":https://sdk.ably.com/builds/ably/#onStatusChange method to create a subscription through which you can asynchronously iterate for the status updates:

```[javascript]
const { off } = chatClient.connection.status.onStatusChange((change) => console.log(change));
```
Expand All @@ -86,6 +99,13 @@ const MyComponent = () => {
};
```

```[swift]
let subscription = chatClient.connection.onStatusChange(bufferingPolicy: .unbounded)
for await statusChange in subscription {
print("Connection status changed to: \(statusChange.current)")
}
```

blang[javascript].
To remove the connection status listener, call the @off()@ function returned in the @subscribe()@ response:

Expand All @@ -101,6 +121,13 @@ blang[javascript].

blang[react].

blang[swift].
To stop the subscription from firing new status events, call its @finish()@ function:

```[swift]
subscription.finish()
```

h2(#discontinuity). Handle connection discontinuity

If a client briefly loses connection to Ably, for example when driving through a tunnel, the SDK will attempt to recover the connection. If the disruption lasts for less than 2 minutes, then on reconnection the SDK will automatically reattach to any rooms and replay any missed messages.
Expand All @@ -112,6 +139,9 @@ blang[javascript].

blang[react].
Any hooks that take an optional listener to monitor their events, such as typing indicator events in the @useTyping@ hook, can also register a listener to be notified of, and handle, periods of discontinuity.

blang[swift].
Each feature of the Chat SDK provides an @subscribeToDiscontinuities()@ method to assist with this. This enables you to create a subscription that will fire an event when discontinuity occurs in that feature so that you can handle it, as needed. As mentioned above, to stop your subscription from firing new events call its @finish()@ method.

For example, for messages:

Expand All @@ -136,6 +166,13 @@ const MyComponent = () => {
};
```

```[swift]
let subscription = room.messages.subscribeToDiscontinuities()
for await error in subscription {
print("Recovering from the error: \(error)")
}
```

blang[react].

blang[javascript].
Expand Down
45 changes: 40 additions & 5 deletions content/chat/rooms/history.textile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ product: chat
languages:
- javascript
- react
- swift
---

The history feature enables users to retrieve messages that have been previously sent in a room. Ably stores chat messages for 24 hours by default. You can extend this up to 30 days by "contacting us":https://forms.gle/SmCLNFoRrYmkbZSf8.
Expand Down Expand Up @@ -50,13 +51,32 @@ const MyComponent = () => {
};
```

```[swift]
let paginatedResult = try await room.messages.get(options: .init(orderBy: .newestFirst))
print(paginatedResult.items)
if paginatedResult.hasNext {
let next = try await paginatedResult.next!
print(next.items)
} else {
print("End of messages")
}
```

The following optional parameters can be passed when retrieving previously sent messages:

|_. Parameter |_. Description |
| start | Earliest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp equal to, or greater than, this value will be returned. |
| end | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned. |
| direction | The direction in which to retrieve messages from; either @forwards@ or @backwards@. |
| limit | Maximum number of messages to be retrieved, up to 1,000. |
blang[javascript].
|_. Parameter |_. Description |
| start | Earliest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp equal to, or greater than, this value will be returned. |
| end | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned. |
| direction | The direction in which to retrieve messages from; either @forwards@ or @backwards@. |
| limit | Maximum number of messages to be retrieved, up to 1,000. |

blang[swift].
|_. Parameter |_. Description |
| start | Earliest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp equal to, or greater than, this value will be returned. |
| end | Latest time to retrieve messages from, as a unix timestamp in milliseconds. Messages with a timestamp less than this value will be returned. |
| orderBy | The direction in which to retrieve messages from; either @oldestFirst@ or @newestFirst@. |
| limit | Maximum number of messages to be retrieved, up to 1,000. |

h2(#subscribe). Retrieve messages sent prior to subscribing

Expand All @@ -68,6 +88,9 @@ blang[javascript].
blang[react].
Use the "@getPrevious()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_react.UseMessagesResponse.html#getPreviousMessages method available from the response of the @useMessages@ hook to only retrieve messages that were received before the listener subscribed to the room. As long as a defined value is provided for the listener, and there are no message discontinuities, @getPreviousMessages()@ will return messages from the same point across component renders. If the listener becomes undefined, the subscription to messages will be removed. If you subsequently redefine the listener then @getPreviousMessages()@ will return messages from the new point of subscription.

blang[swift].
Use the @getPreviousMessages()@ method from your messages subscription to only retrieve messages that were received before the subscription was created:

```[javascript]
const { getPreviousMessages } = room.messages.subscribe(() => {
console.log('New message received');
Expand Down Expand Up @@ -114,6 +137,18 @@ const MyComponent = () => {
};
```

```[swift]
let messagesSubscription = try await room.messages.subscribe(bufferingPolicy: .unbounded)
let paginatedResult = try await messagesSubscription.getPreviousMessages(params: .init(limit: 50)) // `orderBy` here is ignored and always `newestFirst`
print(paginatedResult.items)
if paginatedResult.hasNext {
let next = try await paginatedResult.next!
print(next.items)
} else {
print("End of messages")
}
```

The following parameters can be passed when retrieving previously sent messages:

|_. Parameter |_. Description |
Expand Down
68 changes: 60 additions & 8 deletions content/chat/rooms/index.textile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ product: chat
languages:
- javascript
- react
- swift
---

Rooms are used to organize and logically separate your users and chat messages into 'rooms'. They are the entry object into using chat and provide access to all other chat features, such as messages, online status and typing indicators. A room can represent a 1:1 chat between an agent and a customer, a private message between two users in a chat application, a large group conversation, or the chat section of a livestream with thousands of users.
Expand Down Expand Up @@ -53,6 +54,10 @@ const App = () => {
};
```

```[swift]
let room = try await chatClient.rooms.get(roomID: "basketball-stream", options: RoomOptions())
```

blang[react].

<aside data-type='important'>
Expand All @@ -62,8 +67,11 @@ blang[react].

blang[javascript].

blang[swift].

When you create or retrieve a room using @rooms.get()@, you need to choose which additional chat features you want enabled for that room. This is configured by passing a "@RoomOptions@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.RoomOptions.html object as the second argument. In addition to setting which features are enabled, @RoomOptions@ also configures the properties of the associated features, such as the timeout period for typing indicators.

blang[javascript].
When you create or retrieve a room using @rooms.get()@, you need to choose which additional chat features you want enabled for that room. This is configured by passing a "@RoomOptions@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.RoomOptions.html object as the second argument. In addition to setting which features are enabled, @RoomOptions@ also configures the properties of the associated features, such as the timeout period for typing indicators.

```[javascript]
const presence = {enter: false};
Expand All @@ -84,29 +92,42 @@ blang[javascript].
```[javascript]
const room = chatClient.rooms.get('basketball-stream', {typing: {timeoutMs: 5000}});
```

Enable each feature using its associated option. The details of the options available to each feature are documented on their respective pages:

| Feature | @RoomOption@ | Default settings |
| "Presence":/chat/rooms/presence | @presence@ | @RoomOptionsDefaults.presence@ |
| "Occupancy":/chat/rooms/occupancy | @occupancy@ | @RoomOptionsDefaults.occupancy@ |
| "Typing indicators":/chat/rooms/typing | @typing@ | @RoomOptionsDefaults.typing@ |
| "Room reactions":/chat/rooms/reactions | @reactions@ | @RoomOptionsDefaults.reactions@ |

blang[react].

Enable each feature using its associated option. The details of the options available to each feature are documented on their respective pages:
blang[swift].

| Feature | @RoomOption@ | Default settings |
| "Presence":/chat/rooms/presence | @presence@ | @RoomOptionsDefaults.presence@ |
| "Occupancy":/chat/rooms/occupancy | @occupancy@ | @RoomOptionsDefaults.occupancy@ |
| "Typing indicators":/chat/rooms/typing | @typing@ | @RoomOptionsDefaults.typing@ |
| "Room reactions":/chat/rooms/reactions | @reactions@ | @RoomOptionsDefaults.reactions@ |
```[swift]
let presence = PresenceOptions(enter: false)
let typing = TypingOptions(timeout: 5.0) // seconds
let options = RoomOptions(presence: presence, typing: typing, reactions: nil, occupancy: nil)
let room = try await chatClient.rooms.get(roomID: "basketball-stream", options: options)
```

h3(#release). Release a room

Releasing a room allows the underlying resources to be garbage collected or released.

Releasing a room may be optional for many applications. If you have multiple transient rooms, such as in the case of a 1:1 support chat, then it is may be more beneficial.
Once "@rooms.release()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.Rooms.html#release has been called, the room will be unusable and a new instance will need to be created using "@rooms.get()@":#create if you want to reuse it.

blang[javascript].
Once "@rooms.release()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.Rooms.html#release has been called, the room will be unusable and a new instance will need to be created using "@rooms.get()@":#create if you want to reuse it.

```[javascript]
await rooms.release('basketball-stream');
```

```[swift]
_ = try await rooms.release(roomID: "basketball-stream")
```

blang[react].
By default the @ChatRoomProvider@ will automatically call "@release()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.Room.html#release on the room when it unmounts. Set the "@release@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_react.ChatRoomProviderProps.html#release property to @false@ to change this behavior and have the room only "detach":#detach when the component unmounts. You can manually control this attachment behavior using the "@useRoom@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat_react.useRoom.html hook.
Expand Down Expand Up @@ -142,6 +163,10 @@ const MyComponent = () => {
};
```

```[swift]
try await room.attach()
```

h3(#detach). Detach from a room

blang[javascript].
Expand All @@ -150,6 +175,10 @@ blang[javascript].
```[javascript]
await room.detach();
```

```[swift]
try await room.detach()
```

blang[react].
By default the @ChatRoomProvider@ will automatically call "@release()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.Room.html#release on the room when it unmounts. Set the "@release@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_react.ChatRoomProviderProps.html#release property to @false@ to change this behavior and have the room only "detach":#detach when the component unmounts. You can manually control this attachment behavior using the "@useRoom@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat_react.useRoom.html hook.
Expand Down Expand Up @@ -180,6 +209,9 @@ blang[javascript].
blang[react].
Use the @roomStatus@ property to view the current "@Room@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_js.Room.html status changes. The @roomError@ property is its associated error. Any hooks that take an optional listener have these properties available in their response, such as @useMessages@ or @useTyping@. It is more common that you will monitor the room status in the specific feature hooks rather than needing to use @useRoom@. These events are related to the room instance of the nearest "@ChatRoomProvider@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat_react.ChatRoomProvider.html. For example, with the @useMessages@ hook:

blang[swift].
Use the @status@ property to check which status a room is currently in:

```[javascript]
const currentStatus = room.status.current
```
Expand All @@ -203,6 +235,10 @@ const MyComponent = () => {
};
```

```[swift]
let status = try await room.status
```

blang[javascript].
You can also subscribe to room status updates by registering a listener. An event will be emitted whenever the status of the room changes.

Expand Down Expand Up @@ -243,3 +279,19 @@ blang[react].
return <div>Occupancy Component</div>;
};
```

blang[swift].
You can also create a subscribtion to the room status updates. An event will be emitted whenever the status of the room changes.

```[swift]
let statusSubscription = try await room.onStatusChange(bufferingPolicy: .unbounded)
for await status in statusSubscription {
print("Room status: \(status)")
}
```

To cancel the room status subscribtion, call the provided @finish()@ method:

```[swift]
statusSubscription.finish()
```
25 changes: 25 additions & 0 deletions content/chat/rooms/messages.textile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ product: chat
languages:
- javascript
- react
- swift
---

You can send and receive messages in a chat room with any number of participants. These users subscribe to messages by registering a listener, and send messages to all users that are subscribed to receive them.
Expand All @@ -19,6 +20,9 @@ blang[react].

Providing a listener will also enable you to retrieve messages that have been "previously sent to the room.":/chat/rooms/history

blang[swift].
Subscribe to receive messages in a room by creating a subscription. Use the @messages.subscribe(bufferingPolicy: .unbounded)@ method in a room to receive all messages that are sent to it:

```[javascript]
const {unsubscribe} = room.messages.subscribe((message) => {
console.log(message);
Expand All @@ -40,6 +44,13 @@ const MyComponent = () => {
};
```

```[swift]
let messagesSubscription = try await room.messages.subscribe(bufferingPolicy: .unbounded)
for await message in messagesSubscription {
print("Message received: \(message)")
}
```

h3(#structure). Message structure

The following is the structure of a message:
Expand Down Expand Up @@ -97,6 +108,13 @@ blang[javascript].
blang[react].
When you unmount the component that is using the @useMessages@ hook, it will automatically handle unsubscribing any associated listeners registered to receive messages.

blang[swift].
To cancel the room messages subscribtion, call the provided @finish()@ method:

```[swift]
messagesSubscription.finish()
```

h2(#send). Send a message

blang[javascript].
Expand All @@ -105,6 +123,9 @@ blang[javascript].
blang[react].
Use the "@send()@":https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat_react.UseMessagesResponse.html#send method available from the response of the @useMessages@ hook to to send a message to the room:

blang[swift].
Use the @messages.send()@ method to send a message in a chat room. All users that are subscribed to messages on that room will receive it:

```[javascript]
await room.messages.send({text: 'hello'});
```
Expand All @@ -126,3 +147,7 @@ const MyComponent = () => {
);
};
```

```[swift]
_ = try await room.messages.send(params: .init(text: "hello"))
```
Loading

0 comments on commit 0761952

Please sign in to comment.