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.
Config config = ChatSDK.config();
// Example
config.setGoogleMaps("Google Maps API Key");
let config: BConfiguration = BChatSDK.config()
// Example
config.googleMapsApiKey = "Google Maps API Key"
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
.
BaseNetworkAdapter a = ChatSDK.shared().a();
let networkAdapter = BChatSDK.shared()?.networkAdapter
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:
// 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;
// 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()
// 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
// 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 -> {
});
// 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")
// 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
// 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();
// 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()
// 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
// 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);
// 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)
// 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)
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();
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
// 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);
BChatSDK.hook().add(BHook.init(onMain: { dict in
if let message = dict?[bHook_PMessage] as? PMessage {
print(message.text())
}
}, weight: 10), withNames: [bHookMessageRecieved, bHookMessageWillSend])
[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
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";
#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)
NotificationCenter.default.addObserver(forName: bNotificationLogout, object: nil, queue: nil, using: { notification in
})
[[NSNotificationCenter defaultCenter] addObserverForName:bNotificationLogout object:Nil queue:Nil usingBlock:^(NSNotification * notification) {
}];
#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.
InterfaceAdapter interfaceAdapter = ChatSDK.ui();
let interfaceAdapter: PInterfaceAdapter = BChatSDK.ui()
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.
// Override an activity
ChatSDK.ui().setChatActivity(CustomChatActivity.class);
// Override a fragment
ChatSDK.ui().setProfileFragmentProvider(user -> {
ProfileFragment fragment = new AProfileFragment();
fragment.setUser(user);
return fragment;
});
// 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))
// 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.
StorageManager storageManager = ChatSDK.db();
let storageAdapter: PStorageAdapter = BChatSDK.db()
id<PStorageAdapter> storageAdapter = BChatSDK.db;
The database service can be used to fetch, create, and delete entities. For example:
// 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'");
// 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 {
}
// 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:
user.setName("Test");
user.setAvatarURL("http://something.png");
List<User> users = thread.getUsers();
List<Message> messages = thread.getMessages();
// etc...
user.setName("test");
user.setImageURL("http://something.png")
let users = thread?.users()
let messages = thread?.messagesOrderedByDateNewestFirst()
// etc...
[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.
Last updated