Skip to main content
Quick Reference for AI Agents & Developers
  • Purpose: Keep real-time connection alive when app enters background
  • Enable: Add Background Modes capability → Enable “Background fetch” and “Remote notifications”
  • Behavior: Maintains connection for a few seconds in background
  • Use case: Update UI with new messages when switching between apps
  • Related: Connection Status · WebSocket Connection
In iOS, when the user enters in the background state, real time connection breaks with the server. So, if the user comes inside the chat window or in the conversation list then it won’t update the new messages received from the real time server until it’s being fetched from the API. To keep user interaction alive with the application you can add our service which keeps real time connection alive in a background state for a few seconds. If the user is constantly switching between multiple applications at the same time, this service will help to update real time updates on the UI.

Background updates behaviour

This below table is applicable only when these steps are followed. autoEstablishSocketConnection usage can be found in Managing Web-Socket connections manually.
ValueBehaviour
autoEstablishSocketConnectiontrueConnection is maintained in background for 30 seconds and after that it is killed.
autoEstablishSocketConnectionfalse1. If CometChat.connect() is called and app goes to background the connection is maintained for 30 seconds and after that connection is terminated. 2. If CometChat.disconnect() is called and app goes to background the connection not maintained.
Please follow the steps to prepare your app for background states.

Step 1. Add Background Modes in Capabilities

Click on Targets -> Project -> [+ Capability] -> Add ‘Background Modes’ section.

Step 2. Select Background modes for processing

Select ‘Background Fetch’ and ‘Background Processing’ options by ticking them.

Step 3. Add Code in Application class to configure background services for different states.

Add CometChat.configureServicesmethod in application class or scene delegate class as shown below.
func applicationWillResignActive(_ application: UIApplication) {
        CometChat.configureServices(.willResignActive)
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        CometChat.configureServices(.didBackground)
    }
Method Signature:
ParameterTypeDescription
InputApplicationStateApp lifecycle state enum value
ReturnsVoidNo return value
ApplicationState Enum:
ValueDescription
.willResignActiveApp is about to move from active to inactive state. Called when user presses home button or receives interruption
.didBackgroundApp has fully entered the background state. Called after transition is complete
Application Lifecycle Events:
EventUIApplication MethodCometChat Configuration
App becoming inactiveapplicationWillResignActive(_:)CometChat.configureServices(.willResignActive)
App entered backgroundapplicationDidEnterBackground(_:)CometChat.configureServices(.didBackground)
Background Task Lifecycle Flow:
StepEventActionDescription
1User presses home buttonapplicationWillResignActive calledApp begins transition to background
2Transition completesapplicationDidEnterBackground calledBackground task starts
3Background task runsWebSocket connection maintainedConnection kept alive for ~30 seconds
4Timeout reached (~30s)System terminates taskConnection terminated by iOS
Connection Behavior Based on autoEstablishSocketConnection:
autoEstablishSocketConnectionBackground Behavior
trueConnection maintained for 30 seconds, then killed automatically
false + CometChat.connect() calledConnection maintained for 30 seconds, then terminated
false + CometChat.disconnect() calledConnection not maintained in background
Related Configuration:
SettingLocationDescription
autoEstablishSocketConnectionManaging Web-Socket connections manuallyControls automatic socket connection behavior
Background ModesXcode CapabilitiesMust enable “Background fetch” and “Background Processing”
  1. As per the iOS standard guidelines, this service will keep alive for few seconds in background services in the system. After few seconds it will get terminated automatically by the system.
  2. This service is only available after SDK v4.x.x & UI Kit v4.x.x

Step 4. Check background service is running

You can check the background service is running or not using CometChat.BackgroundTaskEnabled() method. It will return true if service is running else it will return false.
if CometChat.backgroundTaskEnabled() {
  print("Background service is running, it will automatically update UI.")
}else{
  print("Background service is stopped, Please refresh messages or conversations here to update.")
}
Method Signature:
ParameterTypeDescription
InputNoneNo input parameters
ReturnsBoolBackground task running status
Return Values:
Return ValueTypeDescription
trueBoolBackground service is running, real-time updates are active
falseBoolBackground service is stopped, manual refresh required
Usage Scenarios:
ScenariobackgroundTaskEnabled()Recommended Action
App just entered backgroundtrueNo action needed, UI updates automatically
Background timeout reached (~30s)falseRefresh messages/conversations when app returns to foreground
User switches apps quicklytrueReal-time updates continue seamlessly
App in background > 30 secondsfalseCall refresh APIs on viewWillAppear or applicationDidBecomeActive
Integration with UI Components:
StateUI BehaviorRecommended Implementation
trueMessages and conversations update in real-timeNo additional action required
falseUI may be staleShow refresh indicator or auto-fetch on viewWillAppear
Conditional Refresh Pattern:
StepCheckAction
1viewWillAppear calledCheck CometChat.backgroundTaskEnabled()
2Returns falseCall MessagesRequest.fetchPrevious() or ConversationsRequest.fetchNext()
3Returns trueSkip refresh, real-time updates are active
Related Methods:
MethodDescriptionLink
CometChat.configureServices(_:)Configure background servicesSee Step 3 above
CometChat.connect()Manually establish WebSocket connectionManaging Web-Socket connections manually
CometChat.disconnect()Manually close WebSocket connectionManaging Web-Socket connections manually
CometChat.getConnectionStatus()Get current connection statusConnection Status