API Cheat Sheet

A quick reference guide to the Chat SDK API

Code Examples

The demo projects on Github contain some useful code examples.

Configuration

The Chat SDK can be configured using the configuration service.

Java
Swift
Objective C
Java
Config config = ChatSDK.config();
// Example
config.setGoogleMaps("Google Maps API Key");
Swift
let config: BConfiguration = BChatSDK.config()
// Example
config.googleMapsApiKey = "Google Maps API Key"
Objective C
BConfiguration * config = BChatSDK.config;
// Example
config.googleMapsApiKey = @"Google Maps API Key";

Messaging Server API

The Chat SDK uses a series of services to make requests to the messaging server. These services are contained in a class called NetworkAdapter.

Java
Swift
Objective C
Java
BaseNetworkAdapter a = ChatSDK.shared().a();
Swift
let networkAdapter = BChatSDK.shared()?.networkAdapter
Objective C
id<PNetworkAdapter> networkAdapter = BChatSDK.shared.networkAdapter;

Each of these services contains methods to make requests to the server. Here is a full list of the services available:

Java
Swift
Objective C
Java
// Core Methods
CoreHandler core = networkAdapter.core;
AuthenticationHandler auth = networkAdapter.auth;
ThreadHandler thread = networkAdapter.thread;
ImageMessageHandler imageMessage = networkAdapter.imageMessage;
LocationMessageHandler locationMessage = networkAdapter.locationMessage;
ContactHandler contact = networkAdapter.contact;
SearchHandler search = networkAdapter.search;
PublicThreadHandler publicThread = networkAdapter.publicThread;
// Free modules
PushHandler push = networkAdapter.push;
UploadHandler upload = networkAdapter.upload;
// Paid modules
VideoMessageHandler videoMessage = networkAdapter.videoMessage;
AudioMessageHandler audioMessage = networkAdapter.audioMessage;
TypingIndicatorHandler typingIndicator = networkAdapter.typingIndicator;
LastOnlineHandler lastOnline = networkAdapter.lastOnline;
BlockingHandler blocking = networkAdapter.blocking;
NearbyUsersHandler nearbyUsers = networkAdapter.nearbyUsers;
ReadReceiptHandler readReceipts = networkAdapter.readReceipts;
StickerMessageHandler stickerMessage = networkAdapter.stickerMessage;
FileMessageHandler fileMessage = networkAdapter.fileMessage;
EncryptionHandler encryption = networkAdapter.encryption;
Swift
// Core Methods
let core: PCoreHandler = networkAdapter.core()
let auth: PAuthenticationHandler = networkAdapter.auth()
let thread: PThreadHandler = networkAdapter.thread()
let imageMessage: PImageMessageHandler = networkAdapter.imageMessage()
let locationMessage: PLocationMessageHandler = networkAdapter.locationMessage()
let contact: PContactHandler = networkAdapter.contact()
let search: PSearchHandler = networkAdapter.search()
let publicThread: PPublicThreadHandler = networkAdapter.publicThread()
// Free modules
let push: PPushHandler = networkAdapter.push()
let upload: PUploadHandler = networkAdapter.upload()
// Paid modules
let videoMessage: PVideoMessageHandler = networkAdapter.videoMessage()
let audioMessage: PAudioMessageHandler = networkAdapter.audioMessage()
let typingIndicator: PTypingIndicatorHandler = networkAdapter.typingIndicator()
let lastOnline: PLastOnlineHandler = networkAdapter.lastOnline()
let blocking: PBlockingHandler = networkAdapter.blocking()
let nearbyUsers: PNearbyUsersHandler = networkAdapter.nearbyUsers()
let readReceipt: PReadReceiptHandler = networkAdapter.readReceipt()
let stickerMessage: PStickerMessageHandler = networkAdapter.stickerMessage()
let fileMessage: PFileMessageHandler = networkAdapter.fileMessage()
let encryption: PEncryptionHandler = networkAdapter.encryption()
Objective C
// Core Methods
id<PCoreHandler> core = networkAdapter.core;
id<PAuthenticationHandler> auth = networkAdapter.auth;
id<PThreadHandler> thread = networkAdapter.thread;
id<PImageMessageHandler> imageMessage = networkAdapter.imageMessage;
id<PLocationMessageHandler> locationMessage = networkAdapter.locationMessage;
id<PContactHandler> contact = networkAdapter.contact;
id<PSearchHandler> search = networkAdapter.search;
id<PPublicThreadHandler> publicThread = networkAdapter.publicThread;
// Free modules
id<PPushHandler> push = networkAdapter.push;
id<PUploadHandler> upload = networkAdapter.upload;
// Paid modules
id<PVideoMessageHandler> videoMessage = networkAdapter.videoMessage;
id<PAudioMessageHandler> audioMessage = networkAdapter.audioMessage;
id<PTypingIndicatorHandler> typingIndicator = networkAdapter.typingIndicator;
id<PLastOnlineHandler> lastOnline = networkAdapter.lastOnline;
id<PBlockingHandler> blocking = networkAdapter.blocking;
id<PNearbyUsersHandler> nearbyUsers = networkAdapter.nearbyUsers;
id<PReadReceiptHandler> readReceipt = networkAdapter.readReceipt;
id<PStickerMessageHandler> stickerMessage = networkAdapter.stickerMessage;
id<PFileMessageHandler> fileMessage = networkAdapter.fileMessage;
id<PEncryptionHandler> encryption = networkAdapter.encryption;

Examples:

Core Service - Methods connected with the current user

Java
Swift
Objective C
Java
// Push the user's profile data to the server
ChatSDK.core().pushUser().subscribe(() -> {
}, throwable -> {
});
// Get the current user
User user = ChatSDK.core().currentUser();
// Get a user and update their proifle from the server
ChatSDK.core().getUserForEntityID("User Entity ID").subscribe(otherUser -> {
}, throwable -> {
});
Swift
// Push the user's profile data to the server
BChatSDK.core().pushUser()?.thenOnMain({ success in
return success
}, { error in
return error
})
// Get the current user
let user: PUser = BChatSDK.currentUser();
// Get a user and update their proifle from the server
let otherUser: PUser = BChatSDK.core().user(forEntityID: "User Entity ID")
Objective C
// Push the user's profile data to the server
[BChatSDK.core pushUser].thenOnMain(^id(id success) {
return nil;
}, ^id(NSError * error) {
return nil;
});
// Get the current user
id<PUser> user = BChatSDK.currentUser;
// Get a user and update their proifle from the server
id<PUser> otherUser = [BChatSDK.core userForEntityID:@"User Entity ID"];

Auth Service - Methods for Authentication

Java
Swift
Objective C
Java
// Login
ChatSDK.auth().authenticate(AccountDetails.username("Username", "Password")).subscribe(() -> {
}, throwable -> {
});
// Check if user is logged in
boolean isLoggedIn = ChatSDK.auth().isAuthenticated();
// Log out
ChatSDK.auth().logout().subscribe();
Swift
// Login
BChatSDK.auth().authenticate(BAccountDetails.username("username", password: "password"))?.thenOnMain({ success in
return success
}, { error in
return error
})
// Check if user is logged in
let isLoggedIn = BChatSDK.auth().isAuthenticated()
// Log out
BChatSDK.auth().logout()
Objective C
// Login
[BChatSDK.auth authenticate:[BAccountDetails username:@"username" password:@"password"]].thenOnMain(^id(id success) {
return nil;
}, ^id(NSError * error) {
return nil;
});
// Check if user is logged in
bool isLoggedIn = BChatSDK.auth.isAuthenticated;
// Log out
[BChatSDK.auth logout];

Thread Service - Methods related to Conversation Threads

Java
Swift
Objective C
Java
// Create thread
User otherUser = ChatSDK.core().getUserNowForEntityID("EntityID");
ChatSDK.thread().createThread("Name", Collections.singletonList(otherUser)).subscribe(thread1 -> {
// Send a message
ChatSDK.thread().sendMessageWithText("Hi", thread1).subscribe();
});
// Get a list of public threads
List<Thread> threads = ChatSDK.thread().getThreads(ThreadType.Private1to1);
Swift
// Create thread
BChatSDK.thread().createThread(withUsers: [otherUser], name: "Name", threadCreated: { error, thread in
// Send a message
BChatSDK.thread().sendMessage(withText: "Hi", withThreadEntityID: thread?.entityID())
})
// Get a list of public threads
let threads = BChatSDK.thread().threads(with: bThreadType1to1)
Objective C
// Create thread
[BChatSDK.thread createThreadWithUsers:@[otherUser] name:@"Name" threadCreated:^(NSError * error, id<PThread> thread) {
// Send a message
[BChatSDK.thread sendMessageWithText:@"Hi" withThreadEntityID:thread.entityID];
}];
// Get a list of public threads
NSArray * threads = [BChatSDK.thread threadsWithType:bThreadType1to1];

Messaging Server Notifications

Since messaging happens in realtime, we also need to get notifications from the server. This happens through several mechanisms. For more details see:

Some available for Android and others for iOS:

1. Event Bus (Android)

Java
EventType.java
Java
Predicate<NetworkEvent> filter = NetworkEvent.filterType(EventType.MessageAdded, EventType.MessageRemoved);
Disposable d = ChatSDK.events()
.source()
.filter(filter)
.subscribe(networkEvent -> {
// Handle Event Here
if (networkEvent.getMessage() != null) {
Logger.debug(networkEvent.getMessage().getText());
}
});
// Stop listening
d.dispose();
EventType.java
public enum EventType {
ThreadAdded,
ThreadRemoved,
ThreadDetailsUpdated,
ThreadMetaUpdated,
MessageAdded,
MessageUpdated,
MessageRemoved,
MessageSendStatusUpdated,
ThreadUsersUpdated,
ThreadUserRoleUpdated,
UserMetaUpdated,
UserPresenceUpdated,
ContactAdded,
ContactDeleted,
ContactsUpdated,
TypingStateUpdated,
Logout,
ThreadRead,
MessageReadReceiptUpdated,
NearbyUserAdded,
NearbyUserMoved,
NearbyUserRemoved,
NearbyUsersUpdated,
Error
}

2. Hooks

Java
Swift
Objective C
Java
// Hooks
ChatSDK.hook().addHook(Hook.sync(data -> {
Message message = (Message) data.get(HookEvent.Message);
}), HookEvent.MessageReceived);
// Asynchronous code
ChatSDK.hook().addHook(Hook.async(data -> Completable.create(emitter -> {
// ... Async code here
emitter.onComplete();
})), HookEvent.MessageReceived);
Swift
BChatSDK.hook().add(BHook.init(onMain: { dict in
if let message = dict?[bHook_PMessage] as? PMessage {
print(message.text())
}
}, weight: 10), withNames: [bHookMessageRecieved, bHookMessageWillSend])
Objective C
[BChatSDK.hook addHook:[BHook hookOnMain:^(NSDictionary * dict) {
id<PMessage> message = dict[bHook_PMessage];
if (message) {
NSLog(@"%@", message.text);
}
} weight:10] withNames:@[bHookMessageRecieved, bHookMessageWillSend]];

Available Hooks

Android
iOS
Android
public static String DidAuthenticate = "DidAuthenticate";
public static String UserOn = "UserOn";
public static String MessageReceived = "MessageReceived";
public static String MessageWillSend = "MessageWillSend";
public static String MessageSent = "MessageSent";
public static String IsNew_Boolean = "IsNew_Boolean";
public static String DidLogout = "DidLogout";
public static String WillLogout = "WillLogout";
public static String UserDidConnect = "UserDidConnect";
public static String UserWillDisconnect = "UserWillDisconnect";
public static String ContactWillBeAdded = "ContactWillBeAdded";
public static String ContactWasAdded = "ContactWasAdded";
public static String ContactWillBeDeleted = "ContactWillBeDeleted";
public static String ContactWasDeleted = "ContactWasDeleted";
iOS
#define bHookDidAuthenticate @"bHookDidAuthenticate"
#define bHook_AuthenticationType @"bHook_AuthenticationType"
#define bHook_AuthenticationTypeLogin @"login"
#define bHook_AuthenticationTypeSignUp @"signup"
#define bHook_AuthenticationTypeCached @"cached"
#define bHookWillLogout @"bHookWillLogout"
#define bHookDidLogout @"bHookDidLogout"
#define bHookUserOn @"bHookUserOn"
#define bHookContactWillBeAdded @"bHookContactWillBeAdded"
#define bHookContactWasAdded @"bHookContactWasAdded"
#define bHookContactWillBeDeleted @"bHookContactWillBeDeleted"
#define bHookContactWasDeleted @"bHookContactWasDeleted"
#define bHookMessageRecieved @"bHookMessageRecieved"
#define bHookMessageWillSend @"bHookMessageWillSend"
#define bHookMessageSending @"bHookMessageSending"
#define bHookMessageDidSend @"bHookMessageDidSend"
#define bHookMessageWillUpload @"bHookMessageWillUpload"
#define bHookMessageDidUpload @"bHookMessageDidUpload"
#define bHookMessageWillBeDeleted @"bHookMessageWillBeDeleted"
#define bHookMessageWasDeleted @"bHookMessageWasDeleted"
#define bHookAllMessagesDeleted @"bHookAllMessagesDeleted"
#define bHookThreadAdded @"bHookThreadAdded"
#define bHookThreadRemoved @"bHookThreadRemoved"
#define bHookThreadUpdated @"bHookThreadUpdated"
#define bHookThreadUsersUpdated @"bHookThreadUsersUpdated"
#define bHookThreadUserRoleUpdated @"bHookThreadUserRoleUpdated"
#define bHookWillPushUser @"bHookWillPushUser"
#define bHookUserUpdated @"bHookUserUpdated"
#define bHookServerPingFailed @"bHookServerPingFailed"
#define bHookServerConnectionStatusUpdated @"bHookServerConnectionStatusUpdated"
#define bHookGlobalAlertMessage @"bHookGlobalAlertMessage"
#define bHookSettingsUpdated @"bHookSettingsUpdated"
#define bHookInternetConnectivityDidChange @"bHookInternetConnectivityDidChange"
#define bHookUserWillDisconnect @"bHookUserWillDisconnect"

3. Notification Center (iOS Deprecated)

Swift
Objective C
Available Events
Swift
NotificationCenter.default.addObserver(forName: bNotificationLogout, object: nil, queue: nil, using: { notification in
})
Objective C
[[NSNotificationCenter defaultCenter] addObserverForName:bNotificationLogout object:Nil queue:Nil usingBlock:^(NSNotification * notification) {
}];
Available Events
#define bNotificationMessageUpdated @"bNMessageUpdated"
#define bNotificationMessageUpdatedKeyMessage @"bNMessageUpdatedKeyMessage"
#define bNotificationFlaggedMessageAdded @"bNFlaggedMessageAdded"
#define bNotificationFlaggedMessageAdded_PMessage @"bNFlaggedMessageAdded_PMessage"
#define bNotificationFlaggedMessageRemoved @"bNFlaggedMessageRemoved"
#define bNotificationFlaggedMessageRemoved_PMessage @"bNFlaggedMessageRemoved_PMessage"
#define bNotificationThreadRead @"bNThreadRead"
#define bNotificationBadgeUpdated @"bNBadgeUpdated"
#define bNotificationPresentChatView @"bNPresentChatView"
#define bNotificationPresentChatView_PThread @"bNPresentChatView_PThread"
#define bNotificationThreadLastMessageUpdated @"bNThreadLastMessageUpdated"
#define bNotificationThreadLastMessageUpdated_Text @"bNThreadLastMessageUpdated_Text"
#define bNotificationReadReceiptUpdated @"bNReadReceiptUpdated"
#define bNotificationReadReceiptUpdatedKeyMessage @"bNReadReceiptUpdatedKeyMessage"
#define bNotificationTypingStateChanged @"bNTypingStateChanged"
#define bNotificationTypingStateChangedKeyThread @"bNTypingStateChangedKeyThread"
#define bNotificationTypingStateChangedKeyMessage @"bNTypingStateChangedKeyMessage"
#define bNotificationAuthenticationComplete @"bNAuthenticationComplete"

UI Modification Service

Chat SDK provides a way to modify the user interface without forking the library. This can be achieved using the UI server.

Java
Swift
Objective C
Java
InterfaceAdapter interfaceAdapter = ChatSDK.ui();
Swift
let interfaceAdapter: PInterfaceAdapter = BChatSDK.ui()
Objective C
id<PInterfaceAdapter> interfaceAdapter = BChatSDK.ui;

The UI service is used to inject views into the app. It also defines which tabs are displayed and much more. For example, you can override Activites, Fragments, and ViewControllers by subclassing them and injecting them using the UI service.

Java
Swift
Objective C
Java
// Override an activity
ChatSDK.ui().setChatActivity(CustomChatActivity.class);
// Override a fragment
ChatSDK.ui().setProfileFragmentProvider(user -> {
ProfileFragment fragment = new AProfileFragment();
fragment.setUser(user);
return fragment;
});
Swift
// Override the chat view controller
BChatSDK.ui().setChatViewController({ thread -> UIViewController in
return AChatViewController.init(thread: thread)
})
// Override the private threads tab
BChatSDK.ui().setPrivateThreadsViewController(APrivateThreadsViewController.init(nibName: nil, bundle: nil))
Objective C
// Override the chat view controller
[BChatSDK.ui setChatViewController: ^UIViewController *(id<PThread> thread) {
return [[AChatViewController alloc] initWithThread:thread];
}];
// Override the private threads tab
[BChatSDK.ui setPrivateThreadsViewController:[[APrivateThreadsViewController alloc] initWithNibName:nil bundle:nil]];

For more details see:

Local Database

The Chat SDK has a powerful local database that is automatically synchronized with the messaging server. It can be accessed using the database service.

Java
Swift
Objective C
Java
StorageManager storageManager = ChatSDK.db();
Swift
let storageAdapter: PStorageAdapter = BChatSDK.db()
Objective C
id<PStorageAdapter> storageAdapter = BChatSDK.db;

The database service can be used to fetch, create, and delete entities. For example:

Java
Swift
Objective C
Java
// Create entity
User user = ChatSDK.db().createEntity(User.class);
// Fetch an entity with a given ID
Thread thread = ChatSDK.db().fetchEntityWithEntityID("threadEntityID", Thread.class);
// Fetch or create an entity with a given ID
User otherUser = ChatSDK.db().fetchOrCreateEntityWithEntityID(User.class, "userEntityID'");
Swift
// Create entity
if let user: PUser = BChatSDK.db().createEntity(bUserEntity) as? PUser {
}
// Fetch an entity with a given ID
if let thread: PThread? = BChatSDK.db().fetchEntity(withID: "threadEntityID", withType: bThreadEntity) as? PThread {
}
// Fetch or create an entity with a given ID
if let otherUser: PUser = BChatSDK.db().fetchOrCreateEntity(withID: "userEntityID", withType: bUserEntity) as? PUser {
}
Objective C
// Create entity
id<PUser> user = [BChatSDK.db createEntity:bUserEntity];
// Fetch an entity with a given ID
id<PThread> thread = [BChatSDK.db fetchEntityWithID:@"threadEntityID" withType:bThreadEntity];
// Fetch or create an entity with a given ID
id<PUser> otherUser = [BChatSDK.db fetchOrCreateEntityWithID:@"userEntityID" withType:bUserEntity];

Each entity then has many methods that can be used. For example:

Java
Swift
Objective C
Java
user.setName("Test");
user.setAvatarURL("http://something.png");
List<User> users = thread.getUsers();
List<Message> messages = thread.getMessages();
// etc...
Swift
user.setName("test");
user.setImageURL("http://something.png")
let users = thread?.users()
let messages = thread?.messagesOrderedByDateNewestFirst()
// etc...
Objective C
[user setName:@"Test"];
[user setImageURL:@"http://something.png"];
NSArray * users = thread.users;
NSArray * messages = thread.messagesOrderedByDateNewestFirst;
// etc...

Note: Creating an entity locally doesn't automatically add it to the server or populate the data from the server. To do that you have to use the network adapter service.