iOS
Sync Manager Getting Started

SyncManager for iOS

SyncManager for iOS is a SendBird Chat SDK add-on for chat data synchronization that allows you to reliably cache group channels and messages in your iOS client app with minimal effort. When SyncManager is added to your client app, it listens to the events that happen in channels and messages in real-time and executes the background tasks to update the local cache with data queried from SendBird server.

Note: SyncManager for iOS is only applicable to group channels.


Benefits

Simplified integration

SendBird SyncManager is designed to ensure quick and easy implementation that doesn’t require much effort. It can easily be added to your client app so that you are able to benefit from all the advantages of our Chat SDK for iOS.

Better user experience

SyncManager implements local data caching, meaning that group channels and messages are cached in local storage for fast loading in unstable network environments as well as data retrieval in offline mode.


Requirements

The minimum requirements for SyncManager for iOS are:

  • iOS 8.0+
  • SendBird Chat SDK for iOS v3.0.155+

Try the sample app

Our sample app has the core features of SyncManager for iOS. Download the app from our repository on GitHub to get an idea of how to integrate the SyncManager to the Chat SDK and your project.

Download Sample App

Note: The fastest way to see our SyncManager in action is to build your chat app on top of our sample app. Make sure to change the application ID of the sample app to your own. Go to the Create a SendBird application from your dashboard section to learn more.


Download SyncManager for iOS

SendBird SyncManager currently supports iOS, Android, and JavaScript SDKs. You can download SyncManager for iOS from our repository on GitHub.

Download SyncManager


Install SyncManager for iOS

SyncManager for iOS can be installed in two ways: via CocoaPods or Carthage.

CocoaPods

Add SendBirdSyncManager into your Podfile in Xcode as below:

Light Color Skin
Copy
platform :ios, '8.0' 
use_frameworks! 

target YOUR_PROJECT_TARGET do
    pod 'SendBirdSyncManager' 
end

Install SendBird SyncManager Framework through CocoaPods.

Light Color Skin
Copy
$ pod install

Update SendBird SyncManager Framework through CocoaPods.

Light Color Skin
Copy
$ pod update SendBirdSyncManager

Note: SendBirdSyncManager is SendBird Chat SDK-dependent. If you install SendBirdSyncManager, CocoaPods will automatically install the Chat SDK for iOS as well. The minimum required version of SendBird Chat SDK for iOS is 3.0.155 or later.

Carthage

Add SendBirdSyncManager into your Cartfile in Xcode as below:

Light Color Skin
Copy
github "sendbird/sendbird-syncmanager-ios"

Install SendBird SyncManager Framework through Carthage as below:

Light Color Skin
Copy
carthage update

Go to your Xcode project's General settings tab. Then, open <YOUR_XCODE_PROJECT_DIRECTORY>/Carthage/Build/iOS in the Finder window and drag SendBirdSyncManager.framework to the Embedded Binaries section in Xcode. Make sure Copy items if needed is checked and click Finish.


How it works

SyncManager is designed to simplify the process of integrating chat in your iOS client app by leveraging local caching. While SendBird Chat SDK for iOS is highly customizable with a number of atomic features, SyncManager facilitates SDK integration by managing most background operations needed to run chat in your iOS client app.

Event-driven structure

SyncManager has an event-driven architecture that updates the chatting view based on data events. Events received through the WebSocket connection as well as processed data in the cache are delivered to the client app by the SyncManager’s collection delegates and can be leveraged when implementing your view.

Collection

As a key component that can be used for view implementation, the Collection holds items that comprise channel or message data. In your view, a collection instance can be binded to an event delegate to subscribe to events. In the callbacks of the event delegate, you can implement what jobs to execute when a specific type of event happens. The following shows a simple example of how you can create a channel collection and bind it to a collection event handler:

Objective-C
Swift
Light Color Skin
Copy
SBDGroupChannelListQuery *query = [SBDGroupChannel createMyGroupChannelListQuery];
SBSMChannelCollection *channelCollection = [SBSMChannelCollection collectionWithQuery:query];
channelCollection.delegate = self;

// Channel collection delegate
- (void)collection:(SBSMChannelCollection *)collection didReceiveEvent:(SBSMChannelEventAction)action channels:(NSArray<SBDGroupChannel *> *)channels {
    switch (action) {
            case SBSMChannelEventActionInsert: {
            // TODO: Insert channels on the list.
            break;
        }
        case SBSMChannelEventActionUpdate: {
            // TODO: Update channels on the list.
            break;
        }
        case SBSMChannelEventActionRemove: {
            // TODO: Remove channels on the list.
            break;
        }
        case SBSMChannelEventActionMove: {
            // TODO: Move channels on the list.
            break;
        }
        case SBSMChannelEventActionClear: {
            // TODO: Clear all) channels.
            break;
        }
        case SBSMChannelEventActionNone:
        default: {
            break;
        }
    }
}
Light Color Skin
Copy
guard let query = SBDGroupChannel.createMyGroupChannelListQuery() else { return }
let channelCollection = SBSMChannelCollection(query: query)
channelCollection?.delegate = self

// SBSMChannelCollectionDelegate    
func collection(_ collection: SBSMChannelCollection, didReceiveEvent action: SBSMChannelEventAction, channels: [SBDGroupChannel]) {
    switch (action) {
        case .insert:
            // TODO: Insert channels on the list.
            break
        case .update:
            // TODO: Update channels on the list.
                break
        case .remove:
            // TODO: Remove channels on the list.
            break
        case .move:
            // TODO: Move channels on the list.
            break
        case .clear:
            // TODO: Clear all channels.
            break
        case .none:
            break;
    }
}

Background sync

Background sync is a feature of SyncManager that automatically stores data fetched from SendBird server in the local cache. When a collection is created, the background sync process starts running with the given conditions. Background sync should follow the lifecycle of a connection: the pauseSynchronize method is called when a connection is lost and the resumeSynchronize method is called when a connection is established.

For example, even if only 2 out of 12 channels are cached, background sync feeds the uncached SendBird server data to the chatting view so that all 12 channels are displayed. In order for this to happen, the channel collection’s fetch method should be called, and the collection brings the insert event for the two channels from the cache. Then, the uncached 10 channels are synchronized through background sync. After synchronization is completed, another insert event is given for the uncached 10 channels. Through this process, all 12 channels are displayed in the view.

Real-time event sync

Real-time event sync is a feature of SyncManager that listens for real-time events received through the WebSocket connection. When an event arrives, SyncManager identifies it, stores it in the cache, and delivers it to the collection handler with the appropriate action such as insert or remove.

Offline mode

SyncManager ensures your client app is operational during offline mode. If background sync isn’t running because a connection with the server hasn’t been established, the view can display cached data provided by SyncManager. Once a connection is re-established, the resumeSynchronize method resumes background sync for data synchronization.


Implementation guide

This section describes how to implement SyncManager in your iOS client app.

Initialization

Initialize and set up the database for SyncManager as below:

Objective-C
Swift
Light Color Skin
Copy
SBSMSyncManagerOptions *options = [SBSMSyncManagerOptions options];
options.messageCollectionCapacity = 200;
options.messageResendPolicy = SBSMMessageResendPolicyManual;
options.maxFailedMessageCountPerChannel = 5;
[SBSMSyncManager setupWithUserId:connector.userId options:options];
Light Color Skin
Copy
let options = SBSMSyncManagerOptions()
options.messageCollectionCapacity = 200
options.messageResendPolicy = .manual
options.maxFailedMessageCountPerChannel = 5
SBSMSyncManager.setup(withUserId: connector.userId, options: options)
FieldTypeDescription

userId

string

Specifies the ID of the user.

options

SBSMSyncManagerOptions

Specifies the options for how SyncManager works.

The SBSMSyncManagerOptions has the following properties:

Property nameDescription

messageCollectionCapacity

Determines the maximum capacity of messages in a collection related to a chat view. Messages that exceed the maximum capacity are removed. Acceptable values are from 200 to 2,147,483,647. (Default: 2,147,483,647)

messageResendPolicy

Determines the policy for handling failed messages. If delivery of a message fails, SyncManager performs different actions based on the configured policy. Acceptable values are:
- none (default): removes the pending message.
- manual: stores the failed message in the local cache and updates the pending message state as failed.
- automatic: performs the same actions as manual, but also tries to automatically resend the failed message.

automaticMessageResendRetryCount

Determines the maximum number of attempts to resend a failed message. Resend attempts are stopped for messages that have been resent the maximum number of attempts and they remain as failed. The messageResendPolicy value must be set as automatic for this to be applicable. (Default: 2,147,483,647)

maxFailedMessageCountPerChannel

Determines the maximum number of failed messages allowed in a channel. SyncManager deletes the earliest failed message and delivers the remove event through the SBSMMessageCollectionDelegate if the number of failed messages exceeds this limit. (Default: 20)

failedMessageRetentionDays

Determines the number of days to retain failed messages. Once failed messages have been retained for the retention period, they are automatically removed. (Default: 7)

Connection handling

When the Chat SDK is connected to SendBird server, SyncManager fetches the current user’s chat-related data from the server to update the local cache. This enables SyncManager to synchronize the local cache with the channel and message data.

Additional jobs, which detect changes in connection status and notify SyncManager, are needed when data is fetched from the server through the Chat SDK’s connection delegate: the resumeSynchronize and pauseSynchronize methods. The resumeSynchronize should be called in the didSucceedReconnection to run background processes for data synchronization when connected, whereas the pauseSynchronize should be called in the didStartReconnection to pause the background processes when disconnected.

Objective-C
Swift
Light Color Skin
Copy
[SBDMain addConnectionDelegate:self identifier:self.description];

// Connection delegates
- (void)didStartReconnection {
    [SBSMSyncManager pauseSynchronize];
}
- (void)didSucceedReconnection {
    [SBSMSyncManager resumeSynchronize];
}
- (void)didFailReconnection {
}
- (void)didCancelReconnection {
}
Light Color Skin
Copy
SBDMain.add(self, identifier: self.description)

// SBDConnectionDelegate
func didStartReconnection() {
    SBSMSyncManager.pauseSynchronize()
}

func didSucceedReconnection() {
    SBSMSyncManager.resumeSynchronize()
}

func didFailReconnection() {    
}

func didCancelReconnection() {   
}

Note: The SBDMain removeAllConnectionDelegate or SBDMain removeAllChannelDelegate method shouldn’t be called because it not only removes the delegates you’ve added, but also the delegates internally managed by SyncManager.

Clear local cache

The cache can be cleared regardless of connection to SendBird server using the clearCache method.

Objective-C
Swift
Light Color Skin
Copy
[SBSMSyncManager clearCache];
Light Color Skin
Copy
SBSMSyncManager.clearCache()

Note: The clearCache is designed for debugging purposes only. Using it for other purposes isn’t recommended.