SDK Setup Guide
Install the SDK
- Android
- iOS
Octopus is available on Maven Central.
Add the dependencies to your build.gradle file:
dependencies {
// Core SDK functionnalities
implementation("com.octopuscommunity:octopus-sdk:x.x.x")
// SDK UI Components (optional)
implementation("com.octopuscommunity:octopus-sdk-ui:x.x.x")
}
See the Octopus SDK GitHub Release section to get the latest published version.
Octopus can be installed:
In an Xcode project
Open your workspace (.xcworkspace) or your project (.xcodeproj), open the File menu and open Add Package Dependencies. Then, paste the url of the Octopus Community SDK:
https://github.com/Octopus-Community/octopus-sdk-swift.git
On the next window, add both Octopus and OctopusUI to your target.
OR
In a Swift Package
Add the dependency to your package:
dependencies: [
.package(url: "https://github.com/Octopus-Community/octopus-sdk-swift.git", from: "1.0.0"),
],
Add the SDK as a dependency to your target:
.target(
name: "YourTarget",
dependencies: [
.product(name: "Octopus", package: "octopus-sdk-swift"),
.product(name: "OctopusUI", package: "octopus-sdk-swift"),
]
),
Not recommended: Cocoapods
As CocoaPods is starting to be less and less used, some libraries are not available anymore. This is the case of SwiftGrpc on which the Octopus SDK has built its backend exchanges. Hence, if you use the SDK using Cocoapods, you will be using an old version of SwiftGrpc.
If you really have to use the SDK with Cocoapods, here is how to do it:
- Copy the content of our podfile example in your podfile. Pay attention to the fact that the post_install script is setting iOS 14 as minimum requirement and setting
ENABLE_USER_SCRIPT_SANDBOXINGtoNO. - Then you can run
pod install
See the Octopus SDK GitHub Release section to get the latest published version.
Use the SDK
As early as possible in your code, you should initialize the OctopusSDK object.
This object is expecting two things:
- the Octopus Community API key
- the connection mode
You need to know the app managed fields (also called as associated fields) that your community is configured for.
As a reminder, every associated profile fields (nickname, picture and/or bio) of your users will be used in the Octopus Community profile of this user.
The user will only be able to change it in your profile edition interface and the data will be synced to its community profile.
On the oposite, every dissociated profile fields will only be used as prefilled values during Octopus profile creation.
After that, if a user changes its nickname in your app, it won't be reflected in Octopus Community, and the user will be able to change its community nickname in the community part.
- Android
- iOS
At least one app managed field
If your community is having at least one associated field, you will have to create the SSO connection mode with the list of the associated fields.
Call the OctopusSDK initialization function in your Application's onCreate() block:
class YourApplication : Application() {
override fun onCreate() {
super.onCreate()
OctopusSDK.initialize(
context = this, // Application Context
apiKey = "YOUR_API_KEY",
connectionMode = ConnectionMode.SSO(
// The list of associated fields
appManagedFields = setOf(ProfileField.NICKNAME, ProfileField.AVATAR)
)
)
}
}
OR
No app managed fields
When there is no app managed fields (i.e. all fields are dissociated), the API is simpler since you only have to configure it in SSO connection mode.
Call the OctopusSDK initialization function in your Application's onCreate() block:
class YourApplication : Application() {
override fun onCreate() {
super.onCreate()
OctopusSDK.initialize(
context = this, // Application Context
apiKey = "YOUR_API_KEY",
connectionMode = ConnectionMode.SSO()
)
}
}
At least one app managed field
If your community is having at least one associated field, you will have to create the SSO connection mode with:
- the list of the associated fields
- the block that will be called when OctopusSDK needs a logged in user. When this block is called, you should start to display your login process.
- the block that will be called when the user tries to modify some fields related to its profile. When this block is called, you should open the profile edition. This block has a ProfileField optional parameter. It indicates the field that the user tapped to edit if there is one.
import Octopus
/* (...) */
let octopus = try OctopusSDK(
apiKey: "YOUR_API_KEY",
connectionMode: .sso(
.init(
appManagedFields: [.nickname, .picture], // the list of associated fields
loginRequired: {
// Put the code here to open your login flow
},
modifyUser: { fieldToEdit in
// Put the code here to open your profile edition screen
// `fieldToEdit` is the field that has been asked to be edited by the user. Nil if the user tapped on "Edit my profile".
}
)
)
)
OR
No app managed fields
When there is no app managed fields (i.e. all fields are dissociated), the API is simpler since it only requires a callback to display the login flow. When this block is called, you should start to display your login process.
import Octopus
/* (...) */
let octopus = try OctopusSDK(
apiKey: "YOUR_API_KEY",
connectionMode: .sso(
.init(
loginRequired: {
// Put the code here to open your login flow
}
)
)
)
Link your user to the SDK
Your application is managing the connection status of the user and inform the Octopus SDK when the user is connected/disconnected
The connectUser API lets you pass the userId. This userId is the string that will identify your user for Octopus.
It needs to be unique and always refer to the same user.
You can also pass profile information (nickname, bio, picture). These fields will be used differently depending of wether the field is associated (i.e. in the app managed fields that you provided during SDK initialization) or not:
-
if the field is associated, each time the connectUser function will be called, Octopus will update the field in the user's community profile with the data you provided. Hence, the field in the community profile of the user will always be the same value as in its app profile
-
if the field is not associated, the data you provided will only be used to fill the community profile until the user edits its community profile. Once its done, their community profile remains separate from yours, meaning any updates made to your profile will not be reflected in theirs, and vice versa.
This is why you should call the connectUser function as soon as the user profile changes.
Client User Token
For security reasons, to ensure that the connected user is legitimate, the API informing the SDK of a user’s connection
includes a callback that provides a signed token for authentication. In other words, the SDK will request a token from
you when needed to authenticate the user.
Therefore, you must add a route like /generateOctopusSsoToken to your backend to generate this token.
Follow the Generate a signed JWT for SSO guide for more information
- Android
- iOS
Inform the SDK that your user is connected:
≥ 1.6.0OctopusSDK.connectUser(
user = ClientUser(
userId = yourUserId, // Unique identifier of your user
profile = ClientUser.Profile(
nickname = yourUserNickname, // nickname is String?
bio = yourUserBio, // bio is String?
picture = yourUserPicture // A Remote URL or a Local Uri
)
),
tokenProvider = {
// Fetch asynchronously this user token (suspended callback)
// by calling your /generateOctopusSsoToken route
}
)
Check the Community ViewModel Sample for a complete use case.
Deprecated < 1.6.0
OctopusSDK.connectUser(
user = ClientUser(
userId = yourUser.id,
profile = ClientUser.Profile(
nickname = yourUser.name,
bio = yourUser.bio,
avatar = yourUser.picture,
// Age Information:
// - LegalAgeReached = Your user is more than 16 years old
// - Underaged = Your user is less than 16 years old
// - null = You don't know
ageInformation = AgeInformation.LegalAgeReached
)
),
tokenProvider = {
// Return asynchronously this user token (suspended callback)
// by calling your /generateOctopusSsoToken route
}
)
- Inform the SDK that your user is disconnected:
OctopusSDK.disconnectUser()
- Optional: Monitor whether the user is connected to the Octopus platform:
OctopusSDK.isUserConnected
Inform the SDK that your user is connected:
≥ 1.6.0octopus.connectUser(
ClientUser(
userId: yourUser.id,
profile: ClientUser.Profile(
nickname: yourUser.name, // nickname is String?
bio: yourUser.bio, // bio is String?
picture: yourUser.picture // picture is Data?, this Data will be transformed into an UIImage using `UIImage(data:)` so it must be compatible.
)
),
tokenProvider: {
// Fetch asynchronously this user token
// by calling your /generateOctopusSsoToken route
}
)
Deprecated < 1.6.0
octopus.connectUser(
ClientUser(
userId: yourUser.id,
profile: ClientUser.Profile(
nickname: yourUser.name,
bio: yourUser.bio,
picture: yourUser.picture,
ageInformation: .legalAgeReached // if your user is more than 16 years old. Pass .underaged if they are less than 16. Pass nil if you don't know
)
),
tokenProvider: {
// Fetch asynchronously this user token
// by calling your /generateOctopusSsoToken route
}
)
Inform the SDK that your user is disconnected:
octopus.disconnectUser()
Display the Octopus Community UI
Now that you have the SDK properly configured, you can add a button in your app that opens the Octopus Community UI.
- Android
- iOS
- Add the
OctopusHomeContentcomposable to your community screen.
OctopusTheme(...) { // Customize the Octopus Theme here
OctopusHomeContent(
modifier = Modifier.fillMaxSize(),
navController = navController, // Your main NavHostController
onNavigateToLogin = {
// This block will be called when OctopusSDK needs a logged-in user.
// You should launch your login process here.
// Example: navController.navigate(LoginRoute)
// Once the user is logged in, you need to call OctopusSDK.connectUser(...) to link
// them with Octopus
},
// Optional: If your community has at least one associated field:
onNavigateToProfileEdit = { profileField ->
// This block will be called when the user tries to modify some fields related
// to their profile.
// When this block is called, you should open your profile edition screen.
// Example: navController.navigate(ProfileScreen(focusNickname = fieldToEdit == ProfileField.NICKNAME))
// Once the user has edited their profile, you should call OctopusSDK.connectUser(...) to update the Octopus profile.
}
)
}
Check the Community Screen Sample for basic usage.
- Declare other Octopus sub-screens in your main
NavHost:
NavHost(...) { // Your main NavHost
octopusComposables(
navController = navController, // Your main NavHostController
onNavigateToLogin = { ... },
onNavigateToProfileEdit = { ... }
) { backStackEntry, content ->
// Customize the Octopus Theme possibly based on a specific Octopus Screen here
OctopusTheme(...) {
content()
}
}
}
This function registers multiple composable() destinations in your NavGraphBuilder for adding the Octopus SDK navigation flow to your app.
Depending on your use case integration mode check the various samples:
First, import Octopus UI:
import OctopusUI
Octopus handles its own navigation, so you must not embed it in a navigation stack.
@State private var openOctopus = false
var body: some View {
Button("Open Octopus Community") {
openOctopus = true
}.fullScreenCover(isPresented: $openOctopus) {
OctopusHomeScreen(octopus: octopus)
}
}
If you're using a UITabBarController to display the Octopus UI inside a UIHostingController, you might encounter a safe area bug. This is a known bug not related to the Octopus SDK UI. To fix it, you might want to add the UITabBarController children in the code instead of in the Storyboard. Otherwise, you can add a negative padding equal to tabBarController.tabBar.frame.size.height to the OctopusUI.
Main screen's navigation bar
You can customize the look of the navigation bar in the main screen (the posts list).
There are two parameters when displaying the OctopusHomeScreen that affect this navigation bar:
navBarLeadingItem: an enum value that lets you choose what will be displayed in the top left corner.
Its value is either:.logoto display the logo (see Modify the theme).text(TextTitle)to display a text. In the case of a text, we highly encourage you to choose a short text (less than 18 characters). Default value is.logo.
navBarPrimaryColor: iftrue, the background color of the navigation bar will be set to the primary color (see Modify the theme). Otherwise, it will be the default color. Default value isfalse.
Here is how to use these two parameters:
OctopusHomeScreen(
octopus: octopus,
navBarLeadingItem: .text(.init(text: "App Name")),
navBarPrimaryColor: true
)
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Scenario "Custom theme".
Modify bottom safe area
According to your app, you might want to add a bottom padding to the Octopus UI content.
- Android
- iOS
This can be done by using the contentPadding parameter of the OctopusHomeContent composable.
OctopusHomeContent(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 10.dp) // This will add a 10dp padding at the bottom of the Octopus UI
// ...
)
To see a full example of how you can achieve that, you can check the Floating Bottom Navigation Bar Sample.
This can be done by using the bottomSafeAreaInset parameter of the OctopusHomeScreen.
OctopusHomeScreen(
octopus: octopus,
bottomSafeAreaInset: 10 // this will add a 10px safe area at the bottom of the Octopus UI
)
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Embedded Tab.
Modify the theme
The Octopus SDK lets you modify its theme so its UI looks more like yours.
You can modify:
- the colors:
- the primary colors (a main color, a low contrast and a high contrast variations of the main color). Please note that the high contrast variation of the primary color is not used for the moment. If you do not pass a custom value for it, black/white default values will be used.
- the color of the elements (mostly texts) displayed over the primary color. If you do not pass a custom value for it, white/black default value will be used.
- the fonts. You can customize the styles (title1, body2, caption1...) used in the sdk. If you do not pass a custom value for it, default value will be used.
- the logo. This is an image displayed on the Octopus home page and profile creation view. If you do not pass a custom image for it, Octopus logo value will be used.
- (⚠ Android only) the TopAppBar. You can customize the appearance, title, navigation icons, actions, and colors of the TopAppBar. If you do not pass a custom configuration for it, default TopAppBar will be used.
- Android
- iOS
By default, Octopus will rely on your application's MaterialTheme.colorScheme, but you can customize the UI more precisely by surrounding composables with the OctopusTheme:
To do that, you can override the theme by passing it as an environment object:
octopusComposables(
navController = navController
) { backStackEntry, content ->
OctopusTheme(
colorScheme = if (isSystemInDarkTheme()) {
octopusDarkColorScheme(
primary = yourDarkPrimaryColor, // Default: MaterialTheme.colorScheme.primary
primaryLow = lowContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.primaryContainer
primaryHigh = highContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.inversePrimary
onPrimary = yourDarkOnPrimaryColor, // Default: MaterialTheme.colorScheme.onPrimary
background = yourDarkBackgroundColor // Default: MaterialTheme.colorScheme.background
// See the complete list in the sources documentation
)
} else {
octopusLightColorScheme(
primary = yourLightPrimaryColor, // Default: MaterialTheme.colorScheme.primary
primaryLow = lowContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.primaryContainer
primaryHigh = highContrastVersionOfYourPrimaryColor, // Default: MaterialTheme.colorScheme.inversePrimary
onPrimary = yourLightOnPrimaryColor, // Default: MaterialTheme.colorScheme.onPrimary
background = yourLightBackgroundColor // Default: MaterialTheme.colorScheme.background
// See the complete list in the sources documentation
)
},
typography = OctopusTypographyDefaults.typography(
title1 = yourCustomTitle1Style, // Default: TextStyle(fontSize = 26.sp)
title2 = yourCustomTitle2Style // Default: TextStyle(fontSize = 22.sp)
// See the complete list in the sources documentation
),
drawables = OctopusDrawablesDefaults.drawables(
logo = painterResource(R.drawable.your_custom_logo), // Default: R.drawable.ic_octopus_logo
tint = yourLogoTintColor // Default: null (no image tinting)
)
// ... Check the complete parameters list in the sources documentation
) {
content()
}
}
Use the OctopusThemeGenerator to configure your Community theme with a live preview of the various Octopus screens.
All parameters of the theme have default values. Only override the ones that you want to customize. In the following example, you are creating an OctopusTheme with default colors, default fonts except for the title1, and a custom logo:
OctopusTheme(
typography = OctopusTypographyDefaults.typography(
title1 = TextStyle(fontFamily = FontFamily.SansSerif, fontSize = 24.sp)
),
drawables = OctopusDrawablesDefaults.drawables(
logo = painterResource(R.drawable.your_custom_logo)
)
) {
OctopusHomeContent(...)
}
Here is a summary of the impacts of the theme you choose:

Here is a summary of the text styles used in the main screens of the SDK:

Customize the TopAppBar
You can customize the appearance of the TopAppBar in the Octopus SDK screens by providing your own OctopusTopAppBar configuration when setting up the theme. We highly encourage you to choose a short text title (less than 18 characters).
OctopusTheme(
...
topAppBar = OctopusTopAppBarDefaults.topAppBar(
title = { text ->
OctopusTopAppBarTitle(
text = "Your TopAppBar Title", // Default: text
logo = OctopusDrawable(painterResource(R.drawable.your_logo)), // Default: OctopusTheme.drawables.logo
textStyle = yourTopAppBarTextStyle // Default: LocalTextStyle.current
)
},
colors = OctopusTopAppBarDefaults.colors(
containerColor = yourTopAppBarBackgroundColor, // Default: OctopusTheme.colorScheme.background
contentColor = yourTopAppBarContentColor // Default: OctopusTheme.colorScheme.gray900
),
navigationIcon = { type, onClick ->
IconButton(onClick = onClick) {
Icon(
imageVector = when (type) {
NavigationIconType.Back -> YourBackIcon
NavigationIconType.Close -> YourCloseIcon
},
contentDescription = when (type) {
NavigationIconType.Back -> "Navigate back"
NavigationIconType.Close -> "Close"
}
)
}
},
// ... Check the complete parameters list in the sources documentation
)
)
The OctopusTopAppBar will automatically use your theme's color scheme if no specific colors are provided, ensuring consistency across your app.
Advanced Screen-Based Theming
For more complex theming scenarios, you can customize any aspect of the Octopus theme (colors, typography, drawables, TopAppBar) based on the current screen:
octopusComposables(
navController = navController
) { backStackEntry, content ->
OctopusTheme(
colorScheme = when {
// Post Details with branded theme
backStackEntry.destination.hasRoute<OctopusDestination.PostDetails>() -> {
octopusColorScheme().copy(
background = if (isSystemInDarkTheme()) Color.Black else Color.White
)
}
else -> octopusColorScheme()
},
topAppBar = when {
// Home screen with custom TopAppBar theme
backStackEntry.destination.hasRoute<OctopusDestination.Home>() -> {
OctopusTopAppBarDefaults.topAppBar(
title = { text ->
OctopusTopAppBarTitle(text = "My Community")
}
)
}
else -> OctopusTopAppBarDefaults.topAppBar()
}
) {
content()
}
}
To do that, you can override the theme by passing it as an environment object:
OctopusHomeScreen(octopus: octopus)
.environment(
\.octopusTheme,
OctopusTheme(
colors: .init(
primarySet: OctopusTheme.Colors.ColorSet(
main: yourPrimaryColor,
lowContrast: lowContrastVersionOfYourPrimaryColor,
highContrast: highContrastVersionOfYourPrimaryColor
),
onPrimary: contentOverPrimaryColor
),
fonts: .init(
title1: Font.custom("Courier New", size: 26),
title2: Font.custom("Courier New", size: 20),
body1: Font.custom("Courier New", size: 17),
body2: Font.custom("Courier New", size: 14),
caption1: Font.custom("Courier New", size: 12),
caption2: Font.custom("Courier New", size: 10),
navBarItem: Font.custom("Courier New", size: 17)
),
assets: .init(logo: yourLogoAsUIImage)
)
)
All parameters of the theme have default values. Only override the ones that you want to customize. In the following example, you are creating an OctopusTheme with default colors, default fonts except for the title1, and a custom logo:
let octopusTheme = OctopusTheme(
fonts: .init(
title1: Font.custom("Courier New", size: 26)
),
assets: .init(logo: yourLogoAsUIImage)
)
Here is a summary of the impacts of the theme you choose:

Here is a summary of the text styles used in the main screens of the SDK:

If your app supports only light or dark mode, add UIUserInterfaceStyle to your Info.plist with the value Light or Dark to force the SDK to use the mode you specified.
Push Notifications ≥ 1.4.0
To increase user engagement, you can provide informations to the Octopus SDK so your users can receive push notifications when other users interact with them inside the community.
Octopus SDK is not asking for push notification permissions, we let you handle that part where it makes more sense in your app.
- Android
- iOS
If your app does not support Push Notifications yet, you can follow the official Firebase documentation.
Our servers need your service account's private key file to be authorized to send notifications to your app on your behalf.
If you don't have this JSON file yet, follow this tutorial
- In the Firebase console, open Settings > Service Accounts
- Click Generate New Private Key, then confirm by clicking Generate Key.
- Securely store the JSON file containing the key.
More information can be found in the official Firebase documentation
Please send the json file using the online form sent by the Octopus team.
This JSON file is different from the one you are using to configure Firebase in your app (google-services.json)
Once your project is correctly set up for push notifications, you should forward the Firebase Cloud Messaging Token (FCM Token) to the Octopus SDK:
class MessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
// Register the new token with Octopus
OctopusSDK.registerNotificationsToken(token)
}
}
You are in charge of requesting the Notification permission and referencing your messaging service:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
if (checkSelfPermission(POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// Request launcher for notification permission
registerForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
callback = {
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
OctopusSDK.registerNotificationsToken(task.result)
}
}
}
).launch(POST_NOTIFICATIONS)
}
<service
android:name=".notifications.MessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
When you receive a notification message, first check if it is an Octopus notification by calling:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
val isOctopusNotification = remoteMessage.data.isOctopusNotification
if (isOctopusNotification) {
// ... Handle the Octopus notification here (see below)
}
}
If it's the case, display the Octopus notification using the Notification Manager:
val octopusNotification = OctopusSDK.getOctopusNotification(data = remoteMessage.data)
if (octopusNotification != null) {
notificationManager.notify(
octopusNotification.id,
Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notification)
.setColor(getColor(R.color.accent))
.setAutoCancel(true)
// Extension function to extract the title, text and deep link from the OctopusNotification
.setOctopusContent(
context = this,
activityClass = MainActivity::class,
octopusNotification = octopusNotification
).build()
)
}
- The
activityClassmust be the one containing the compose content with theoctopusNavigation()subgraph. - The
setOctopusContentfunction is based on a deep link mechanism that will automatically launch the activity and navigate to the corresponding screen within the Octopus navigation graph. - You can also handle the content manually by using the
OctopusNotification'stitle,body, andlinkPathfields and configuring your ownPendingIntent.
If your app does not support Push Notifications yet, you can follow the official Apple documentation.
Our servers need to have a key in the .p8 format in order to send push notifications to your app on your behalf.
If you don't have this key yet, follow this tutorial
- Go to the Apple Dev Website and create a new key.
- Name it and check
Apple Push Notifications service (APNs). - Click on configure for this line and select
Sandbox & Productionin theEnvironmentmenu if you intend to have the same key for sandbox and production builds. - Download the key and be sure to store it in a secure and retrievable place.
Once you have that file, you should send it using the secure form provided by the Octopus Team, along with:
- the key ID: can be found in the list of keys on the Apple Dev Website
- your Bundle ID: can be found in your Xcode project
- your Team ID: can be found here in the
Membership detailscard
Once your project is correctly set up for push notifications, you should forward the notification device token to the Octopus SDK:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
octopus.set(notificationDeviceToken: token)
}
You are in charge of registering for remote notifications by calling:
UIApplication.shared.registerForRemoteNotifications()
and for getting the user's authorization by calling:
notifCenter.requestAuthorization(options: [.alert, .badge, .sound])
When you receive a notification response (i.e., when the user tapped a notification), first check if it is an Octopus notification by calling:
OctopusSDK.isAnOctopusNotification(notification: notificationResponse.notification)
If it is one, display the Octopus UI and pass it the notification response as a Binding:
OctopusHomeScreen(octopus: octopus, notificationResponse: $octopusNotification)
Not seen notifications ≥ 1.3.0
To increase user engagement, let your users know that they have new notifications from the Octopus notification center. Displaying a badge with the number of new notifications in your app can be a great way to suggest your users to look at what's new in the community again.
- Android
- iOS
To do that, the Octopus SDK exposes a val notSeenNotificationsCount: Flow<Int>
that you can collect:
OctopusSDK.notSeenNotificationsCount.collect {}
If you want to update this value with the latest count, simply call:
OctopusSDK.updateNotSeenNotificationsCount()
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Octopus Sample app.
To do that, the Octopus SDK exposes a @Published var notSeenNotificationsCount: Int.
If you want to update this value with the latest count, simply call :
try await octopus.updateNotSeenNotificationsCount()
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Scenario "Notification Badge".
Analytics
Octopus Community provides analytics to help you better understand your users' behavior within the community. To improve the quality of these analytics, we offer features that allow you to provide additional information about your users.
Custom events ≥ 1.4.0
You can tell the SDK to register a custom event. This event can be merged into the reports we provide.
- Android
- iOS
OctopusSDK.track(
event = TrackerEvent.Custom(
name = "Purchase",
properties = mapOf(
"price" to TrackerEvent.Custom.Property(
value = String.format(Locale.US, "%.2f", 1.99)
),
"currency" to TrackerEvent.Custom.Property(value = "EUR"),
"product_id" to TrackerEvent.Custom.Property(value = "product1")
)
)
)
try await viewModel.octopus?.track(customEvent: CustomEvent(
name: "Purchase",
properties: [
"price": .init(value: "\(String(format: "%.2f", 1.99))"),
"currency": .init(value: "EUR"),
"product_id": .init(value: "product1"),
]))
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Scenario "Custom events".
Community Visibility ≥ 1.3.0
If you enable access to the community for only a subset of your users and want the analytics we provide to take this into account, you can inform the SDK accordingly.
This information is reset at each SDK launch so be sure to call the function everytime and as soon as possible after SDK init.
This section is only usefull when the host app (i.e. your app) manages its own A/B testing logic. Call this if your app is running its own A/B test and you want Octopus to log whether a given user is in the "community-enabled" or "control" group. This is useful for reporting and engagement analytics, but does not change the SDK’s runtime behavior.
- Android
- iOS
OctopusSDK.trackAccessToCommunity(hasAccess = canAccessCommunity)
Deprecated < 1.6.0
OctopusSDK.setHasAccessToCommunity(canAccessCommunity)
octopus.track(hasAccessToCommunity: canAccessCommunity)
Deprecated < 1.6.0
octopus.set(hasAccessToCommunity: canAccessCommunity)
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Scenario "Track A/B Tests".
Bridges ≥ 1.5.0
Octopus provides a way of linking a specific object in your app (e.g. a page, a product, any kind of content) to a dynamic post in the community, created automatically. We call this a bridge. To create a bridge, your content (an article, a product, etc.) must have a unique identifier. This ID will be used to link your content to the post. It will also allow users in the Octopus Community to directly view your content.
The bridge process involves four main steps:
Step 1: Prepare the post data Use the SDK to get (or create) the ID of the post related to your content. First get from the SDK the id of the post to display. The SDK will create the post if it is not already created. To do that, call the dedicated API and pass the required data:
- Content id (called clientObjectId) that the post will be about
- Title of the post. It must be between 10 and 3000 characters..
- Catchphrase (optional). It will be displayed below the title, in bold. You can use something like "What do you think about this?". It must be less than 84 characters and we recommand between 6 and 38 characters.
- Image for the post (optional). You can either pass a remote image using an URL or a local image.
The image must respect these requirements:
- File size must be less than 50Mb
- File format must be jpg or png
- Image sides must be between 50px and 4000px, with a max ratio of 32:9 (bigger side / smaller side)
- If you pass a remote image, the resource should be public
- Text of the button that will invite your users to display your content (optionnal). You can use something like "Buy it" if your content is a purchasable product, or "Read the article" if it is a press article. When the button containing this text will be tapped, the SDK will ask you to display your content. If no text is provided, the button won't be displayed. It must be less than 28 characters, we recommand between 4 and 28 characters.
- Topic id (optional). This is the id of the topic that you want the post to be labelled with. If not provided, the topic will be automatically set according to your community settings. You can retrieve the list of the available topics with the dedicated API (see below).
- Android
- iOS
// Get cached topics
OctopusSDK.topics.collect { topics ->
// List of available topics
}
// Fetch latest topics from server
OctopusSDK.fetchTopics()
// Get cached topics
octopus.$topics
.sink { topics in
// List of available topics
}
// Fetch latest topics from server
octopus.fetchTopics()
- Signature (optional). For security reasons, to ensure that the request is coming from you, you can provide a signature. The need for the signature is based on your community settings, we highly encourage you to enable this security check by contacting us. Therefore, you must add a route like
/generateBridgeSignatureto your backend to generate this token based on the same algorithm as generating the token for users (subis not required for this process).
- Android
- iOS
val clientPost = ClientPost(
objectId = "recipe-129302938", // A unique identifier for your content
text = "The perfect Canelés", // Between 10 and 3000 chars
attachment = Image.Remote(url = imageUrl), // You can also pass Image.Local(uri)
topicId = foodRecipeId, // The id of the Octopus topic. Null if default.
catchPhrase = "Tried the canelés? Tell us how good they were!", // Less than 84 characters
viewObjectButtonText = "Read the recipe", // Less than 28 characters
signature = token
)
let postContent = ClientPost(
clientObjectId: "recipe-129302938", // a unique identifier for your content
topicId: foodRecipeId, // the id of the Octopus topic. Nil if default.
text: "The perfects Canelés", // between 10 and 3000 chars
catchPhrase: "Tried the canelés? Tell us how good they were!", // Less than 84 characters
attachment: .localImage(image.jpegData(compressionQuality: 1)!), // you can also pass .distantImage(url)
viewClientObjectButtonText: "Read the recipe", // Less than 28 characters, not displayed if you did not set any `displayClientObjectCallback`
signature: token
)
Step 2: Get the post ID
Calling the API with the previously created post data will return a post ID. With this ID, you can display the post using the Octopus UI. If the post is not created, this API will create it, otherwise it won't change its content.
- Android
- iOS
val result = OctopusSDK.fetchOrCreateClientObjectRelatedPost(clientPost)
when (result) {
is OctopusResult.Success -> {
val post = result.data
val postId = post.id
// Navigate to the post or handle success
}
is OctopusResult.Error -> {
// Handle error
}
}
let post = try await octopus.fetchOrCreateClientObjectRelatedPost(content: postContent)
let postId = post.id
Deprecated < 1.7.0
let postId = try await octopus.getOrCreateClientObjectRelatedPostId(content: postContent)
Step 3: Handle user interaction
Optionally, you can register a callback to be notified when a user wants to view your content from a bridge post. The SDK will provide the clientObjectId so you can open the appropriate content.
- Android
- iOS
// In your NavHost setup
octopusComposables(
// ...
onNavigateToClientObject = { objectId ->
// Display the content that has the given objectId
}
)
octopus.set(displayClientObjectCallback: { objectId in
// display the content that has the given objectId
})
Note that if you don't set the displayClientObjectCallback, the button containing the viewClientObjectButtonText you passed in the ClientPost won't be displayed.
Step 4: Display the post
Using the post id, you can display it directly after the user taps a button on your object page:
- Android
- iOS
OctopusPostDetailsContent(
modifier = Modifier.fillMaxSize(),
postId = postId,
// ...
)
OctopusHomeScreen(octopus: octopus, postId: postId)
Optional: accessing live data about the post > 1.7.0
Additionaly to the post id, we also provide more information about the post. You can access and display the reaction count that all Octopus users did on the post, the number of comments and the number of views.
You can retrieve an object that references the post and that will be updated with the current value and as soon as you call the fetchOrCreateClientObjectRelatedPost function.
- Android
- iOS
OctopusSDK.getClientObjectRelatedPostFlow(clientObjectId = "recipe-129302938")
.filterNotNull()
.collect { post ->
val reactions = post.reactions // Reactions is List<OctopusReactionCount> and OctopusReactionCount is a data class with a reaction and a count
val commentCount = post.commentCount
val viewCount = post.viewCount
}
octopus.getClientObjectRelatedPostPublisher(clientObjectId: "recipe-129302938")
.sink { post in
let reactions = post.reactions // reactions is [OctopusReactionCount] and OctopusReactionCount is a struct with a reaction and a count
let commentCount = post.commentCount
let viewCount = post.viewCount
}
To see a full example of how you can achieve that, you can follow how it is done in the Samples:
- Android
- iOS
in the Octopus Sample app.
The MainViewModel is in charge of preparing the client post and getting the post.
in the Scenario "Bridge to Client Object".
The RecipeViewModel is in charge of preparing the client post and getting the post id and the BridgeToClientObjectViewModel
is in charge of setting the callback.
Octopus A/B Testing ≥ 1.6.0
The A/B test feature lets you measure the impact of the community on your app usage by splitting your audience into two cohorts:
- Test group: a portion of users (e.g., 30%) with full access to the community.
- Control group: the remaining users (e.g., 70%) without access. For them, when they tap the community button, Octopus displays a screen: “The community is not available yet for you, please come back later.” In Octopus Analytics, you’ll then see clear comparisons between these two cohorts in terms of app session volume and retention.
Even if this A/B Test is totally internal, we let you know whether the user can access the community or not (i.e., in which group the user is).
We also let you override the group assigned to the connected user. This can be useful during your tests to check what will see the users of each group or even to provide or disable access to some given users.
Use this method when you need to guarantee that the user’s community access is enforced by Octopus, regardless of internal A/B testing rules.
Here is how to override the user community access:
- Android
- iOS
OctopusSDK.overrideCommunityAccess(hasAccess = canAccessCommunity)
Here is how to know whether the current user has access to the community. It is a published value that is updated as soon as the user group changes. ≥ 1.6.1
OctopusSDK.hasAccessToCommunity.collect { hasAccessToCommunity ->
// Use the hasAccessToCommunity new value
}
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Octopus Sample app.
octopus.overrideCommunityAccess(canAccessCommunity)
Here is how to know whether the current user has access to the community. It is a published value that is updated as soon as the user group changes. ≥ 1.6.1
// one shot value
let hasAccess = octopus.hasAccessToCommunity
// published value
octopus.$hasAccessToCommunity.sink { hasAccessToCommunity in
// use the hasAccessToCommunity new value
}
To see a full example of how you can achieve that, you can follow how it is done in the Samples, in the Scenario "Force Octopus A/B Tests Cohort".
Follow the Samples
Want to see a code examples on how to use the SDK, no worries, we have that for you!
- Android
- iOS
-
First, clone the OctopusSDK project
-
Add those lines to the root project
local.propertiesfile:OCTOPUS_API_KEY=YOUR_API_KEY
OCTOPUS_SSO_CLIENT_USER_TOKEN_SECRET=YOUR_USER_TOKEN_SECRETReplace
YOUR_API_KEYwith your own API key andYOUR_USER_TOKEN_SECRETwith your own token secret. -
According to your connection mode:
- If your are in SSO without any app managed fields:
- Run the
samples.sso.octopus-profileapp
- Run the
- If your are in SSO with all app managed fields:
- Run the
samples.sso.client-profileapp
- Run the
- If your are in SSO with some app managed fields:
- In the
samples/hybrid-profile'sSampleApplication, set the fields that are associated inappManagedFields. - Run the
samples.sso.hybrid-profileapp
- In the
- If your are in SSO without any app managed fields:
-
First, clone or download the code (SDK+Sample are placed on the same git repository):
-
Rename the
secrets.placeholder.xcconfigassecrets.xcconfig -
According to your connection mode, this matches how your app should integrate the SDK:
- If your are in SSO without any app managed fields:
- In
secrets.xcconfig, replaceOCTOPUS_SSO_NO_MANAGED_FIELDS_API_KEYwith your own API key - Open the third tab
More, then tap on the SSO Connection cell and then the No App Managed Fields.
- In
- If your are in SSO with all app managed fields:
- In
secrets.xcconfig, replaceOCTOPUS_SSO_ALL_MANAGED_FIELDS_API_KEYwith your own API key - Open the third tab
More, then tap on the SSO Connection cell and then the With all App Managed Fields.
- In
- If your are in SSO with some app managed fields:
- In
secrets.xcconfig, replaceOCTOPUS_SSO_SOME_MANAGED_FIELDS_API_KEYwith your own API key - In
SSOWithSomeAppManagedFieldsViewModel, set the fields that are associated inappManagedFields. - Open the third tab
More, then tap on the SSO Connection cell and then the Some App Managed Fields.
- In
- If your are in SSO without any app managed fields: