The QuickBlox Developer Hub

Welcome to the QuickBlox developer hub. You'll find comprehensive guides and documentation to help you start working with QuickBlox as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    

This is a beta version of our new React Native documentation for beta version of React Native SDK. Please contact our Customer Support Portal to provide your feedback, suggestions, and requests to improve this page.

Messaging API is built on top of Real-time (XMPP) protocol. In order to use it you need to setup real-time connection with QuickBlox Chat server and use it to exchange data. By default Real-time Chat works over secure TLS connection.

Connect to Chat server

To connect to Chat server use the code snippet below:

QB.chat
  .connect({
    userId: 12345,
    password: 'passw0rd!'
  })
  .then(function () {
    // connected successfully
  })
  .catch(function (e) {
    // some error occurred
  });

Check if connected to Chat server

Check the connection state using the following code snippet.

QB.chat
  .isConnected()
  .then(function (connected) { // boolean
    // handle as necessary, i.e.
    // if (connected === false) reconnect()
  })
  .catch(function (e) {
    // handle error
  });

Disconnect from Chat server

Disconnect from the Chat server using the snippet below:

QB.chat
  .disconnect()
  .then(function () {
    // disconnected successfully
  })
  .catch(function (e) {
    // handle error
  });

Reconnection

The SDK reconnects automatically when the connection to the Chat server is lost. There is a way to disable it and then manage it manually:

QB.settings
  .enableAutoReconnect({ enable: false })
  .then(function () {
    // done
  })
  .catch(function (e) {
    // handle error
  });

Chat in Background

To handle chat offline messages correctly do QB.chat.disconnect when an app goes to background and QB.chat.connect when an app goes to the foreground.

import { AppState } from 'react-native'
import QB from 'quickblox-react-native-sdk'

AppState.addEventListener('change', trackAppState)

function trackAppState (appState) {
  if (appState.match(/inactive|background/)) {
    QB.chat
      .disconnect()
      .then(function () { /* disconnected successfully */ })
      .catch(function (e) { /* handle error */ });
  } else {
    QB.chat
      .connect({
      	userId: 12345,
	      password: 'passw0rd!'
    	})
      .then(function () { /* connected successfully */ })
      .catch(function (e) { /* some error occurred */ });
  }
}

Dialogs

All chats between users are organized in dialogs. There are 3 types of dialogs:

  • 1-1 dialog - a conversation between 2 users.
  • group dialog - a conversation between the specified list of users.
  • public dialog - an open conversation. Any user from your app can subscribe to it.

You need to create a new dialog and then use it to chat with other users. You also can obtain a list of your existing dialogs.

Create a new dialog

Create 1-1 dialog

You need to pass QB.chat.DIALOG_TYPE.CHAT as a type and an id of an opponent you want to create a chat with:

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.CHAT,
    occupantsIds: [12345]
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

Create group dialog

You need to pass QB.chat.DIALOG_TYPE.GROUP_CHAT as a type and ids of opponents you want to create a chat with:

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.GROUP_CHAT,
    name: 'Group Chat',
    occupantsIds: [12345, 12346, 12347]
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

Create public dialog

It's possible to create a public dialog, so any user from your application can subscribe to it. You need to pass QB.chat.DIALOG_TYPE.PUBLIC_CHAT as a type to create a public dialog:

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.PUBLIC_CHAT,
    name: 'Awesome Public Chat'
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

Retrieve a list of dialogs

It's common to request all your conversations on every app login:

QB.chat
  .getDialogs()
  .then(function (result) {
    // result.dialogs - array of dialogs found
    // result.skip - number of items skipped
    // result.limit - number of items returned per page
    // result.total - total amount of items
  })
  .catch(function (e) {
    // handle error
  });

It will return all your 1-1 dialogs, group dialogs and also public dialogs you are subscribed to.

Note

If you want to retrieve only conversations updated after some specific date time, you can pass the filter. This is useful if you cache conversations somehow and do not want to obtain the whole list of your conversations on every app start.

Update dialog’s name and/or participants

User can update a group dialog name and occupants using the snippet below:

const update = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  addUsers: [12340],
  removeUsers: [12345],
  name: 'Team room'
};

QB.chat
  .updateDialog(update)
  .then(function (updatedDialog) {
    // handle as necessary
  })
  .catch(function (e) {
    // handle error
  });

Important

Only group dialog owner and admins can remove other users from a group dialog.

Remove dialog

The following snippet is used to delete a conversation:

QB.chat
  .deleteDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () {
    // dialog was removed successfully
  })
  .catch(function (e) {
    // handle error
  });

Pay attention

Only dialog owner can remove the conversation for all users.

Chat history

Every chat conversation stores its chat history which you can retrieve:

QB.chat
  .getDialogMessages({
    dialogId: 'dsfsd934329hjhkda98793j2',
    sort: {
      ascending: false,
      field: QB.chat.MESSAGES_SORT.FIELD.DATE_SENT
    },
    markAsRead: false
  })
  .then(function (result) {
    // result.messages - array of messages found
    // result.skip - number of items skipped
    // result.limit - number of items returned per page
  })
  .catch(function (e) {
    // handle error
  });

If you want to retrieve chat messages that were sent after or before a specific date-time only you can use the filter. This is useful if you implement pagination for loading messages in your app.

Pay attention

All retrieved chat messages will be marked as read after the request. If you decided not to mark chat messages as read, then make sure you've added the following parameter to your request: markAsRead: false.

Send/Receive chat messages

Receive messages

In order to receive notification from SDK about a new incoming message you have to subscribe to such events:

QB.chat
  .subscribeMessageEvents({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () { })
  .catch(function (e) { /* handle error */ });

After subscribing to message events you have to set up events listener to handle different connection states, message events, etc.):

import { NativeEventEmitter } from 'react-native'
import QB from 'quickblox-react-native-sdk'

const emitter = new NativeEventEmitter(QB.chat);

// every event have following signature
// {
// type - event name (string)
// payload - event data (if any)
// }

function connectionEventHandler(event) {
  // handle connection event
}

function receivedNewMessage(event) {
  const { type, payload } = event
  // handle new message
  // type - event name (string)
  // payload - message received (object)
}

function messageStatusHandler(event) {
  // handle message status change
}

function systemMessageHandler(event) {
  // handle system message
}

function userTypingHandler(event) {
  // handle user typing / stopped typing event
}

const QBConnectionEvents = [
  QB.chat.EVENT_TYPE.CONNECTED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED_ON_ERROR,
  QB.chat.EVENT_TYPE.RECONNECTION_FAILED,
  QB.chat.EVENT_TYPE.RECONNECTION_SUCCESSFUL,
]

QBConnectionEvents.forEach(eventName => {
  emitter.addListener(eventName, connectionEventHandler)
})

emitter.addListener(
  QB.chat.EVENT_TYPE.RECEIVED_NEW_MESSAGE,
  receivedNewMessage
)

emitter.addListener(
  QB.chat.EVENT_TYPE.MESSAGE_DELIVERED,
  messageStatusHandler
)

emitter.addListener(
  QB.chat.EVENT_TYPE.MESSAGE_READ,
  messageStatusHandler
)

emitter.addListener(
  QB.chat.EVENT_TYPE.RECEIVED_SYSTEM_MESSAGE,
  systemMessageHandler
)

emitter.addListener(
  QB.chat.EVENT_TYPE.USER_IS_TYPING,
  userTypingHandler
)

emitter.addListener(
  QB.chat.EVENT_TYPE.USER_STOPPED_TYPING,
  userTypingHandler
)

Pay attention

Messages from group & public chat dialogs will be received in this callback only after you join the dialogs.

1-1 dialog

To send a message to 1-1 dialog use the code snippet below:

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'Hey there!',
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* send successfully */ })
  .catch(function (e) { /* handle error */ })

Group/public dialog

Join group/public dialog

Before you start chatting in a group/public dialog, you need to join it by calling join method:

QB.chat
  .joinDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () { /* joined successfully */ })
  .catch(function (e) { /* handle error */ })

Send a message to group/public dialog

To send/receive messages to the group/public dialog use the following code snippet:

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'Hey there!',
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* send successfully */ })
  .catch(function (e) { /* handle error */ })

Note

Use the same code snippet to send/receive messages for 1-1 dialog, group dialog, and public dialog.

Leave group/public dialog

You can leave the group/public dialog by calling leaveDialog method:

QB.chat
  .leaveDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () { /* left successfully */ })
  .catch(function (e) { /* handle error */ })

Chat


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.