Links

Interaction SDK v2

How to build Experiences into your products using the new Monterosa / Interaction SDK v2
Please contact our sales team if you're interested in access to the Monterosa / Interaction SDK v2.
If you want to move quickly and integrate our pre-existing Experiences into your existing app or site, we recommend starting with Embed Experiences using the SDK.
Monterosa / Interaction SDK offers you more control of the Experience, being able to create your own interactive Elements, achieve further customisation of the UI, and creating an Experience that better fits your product so that you can better engage your users. This is achieved by providing access to the information flowing through our platform using InteractKit, allowing you to rapidly build your own Experience, while leveraging the scalability, speed and content management capabilities of the Monterosa / Interaction Cloud.
Use Cases include:
  1. 1.
    Customise an existing Experience with your own UI – create your own look and feel for votes, quizzes and predictions and more and add these to your existing native or web apps. For example creating a custom layout for a Player Rater.
  2. 2.
    Create your own Experience from the start – If you have a voting, quiz or prediction concept that isn't an existing Experience you can create it using the SDK to create a new application. For example creating a new predictor for a sport we don't support yet.
  3. 3.
    Create your own new experience and use it as a template – If you want to build a web experience and provide this experience to all users within you organisation, you can build it in the Javascript SDK and store this in your Experiences tab for all your teams to re-use whenever they wish. Monterosa internal teams and development partners use this to help them support their customers at scale.
This guide primarily focusses on customising existing experiences, with further guides coming soon that help you create a fresh Experience in the platform.

Core SDK concepts

Before starting, we recommend reviewing Core Concepts to understand how Monterosa / Interaction Cloud works in more detail.
From a development perspective, we have a hierarchy of concepts as follows:
  • Project: a Project matches the Studio Project, and allows you to access the data you enter there, becoming a configuration and management environment for your App.
    • Event: an Event is a representation of a live event in the real world, such as a football match, a concert, the airing of a TV-show, or even the month of June. It is characterised by its start and end times, and contains a set of Elements on the Timeline. It is "owned" by the Project it belongs to. Events are part of a Schedule, and can be manually started, scheduled or manipulated using the Control API for example via sports data feeds.
      • Element: an Element is a bi-directional interactive component that is triggered to appear at a certain time in the event. The Element will contain the required information needed to specify its appearance, its content, and the way it behaves, as well as offering answer functionality so you can gather responses from your audience. Elements also are used for non-interactive content like Articles, Videos, or Images, amongst many others.
  • App: the platform serves up interactive, real-time web and native applications known in the platform as simply Apps. Using Build you can create your own App, associating it with one or more Projects for management and deployment. Apps are defined using a collection of configuration files, known collectively as the App Spec. You can create and customise your own App Spec whilst building an Experience for it.
  • Experience: Experiences are Apps which have been made available within Studio for self-service deployment via the Experiences tab. If you are building a Javascript App then it can become an Experience available to your teams to deploy in the self-service Experiences workflow from Studio. Native mobile apps are not yet supported in the Experiences workflow, but you can still develop your own native mobile apps.
  • Fields: Projects, Events and Elements each have an associated set of fields. These are key-value pairs where the set of keys available to customise and the type of data they'll contain is configured in the App Spec, whilst the value is configured via Studio. Thanks to this configurability, you can create infinite number of distinct Projects, Events and Elements.
An example of a customisable set of fields for a Project

Getting started

You should first follow the steps outlined in the "Getting started" section of the "Embedding Experiences using the SDK" page.
Once the initial setup is done, you will need to add InteractKit as a dependency on your codebase, as InteractKit is the library of our SDK that provides access to bi-directional data flows. You can add InteractKit as follows:
iOS
Android
Javascript
If you use Swift Package Manager, add the following GIT repository URL as a new package dependency in Xcode:
https://<package-username>:<package-token>@gitlab.com/monterosa-sdk/ios.git
Finally, select MonterosaSDKInteractKit from the list of available Package Products.
​
If you use CocoaPods, the GIT repository source URL should already be in your Podfile, so you'll just need to add the following pod dependency:
pod 'MonterosaSDKInteractKit'
Add the following Interaction SDK packages as dependencies to the app-level build.gradle:
dependencies {
...
implementation "co.monterosa.sdk:interactkit"
...
}
NPM should already have been setup to locate the Monterosa / Interaction SDK packages, so we just need to install the InteractKit package:
npm install @monterosa-sdk/interact-kit
Important: You still need to include all Stable polyfills for environments that don't support the features required by Monterosa / Interaction SDK.
Your IDE should help with importing InteractKit, here are some examples:
JavaScript
iOS
Android
import {
getProject,
getEvents,
...
} from '@monterosa-sdk/interact-kit';
import MonterosaSDKInteractKit
import co.monterosa.sdk.interactkit.*

Building your own Experience

Utilising dynamic runtime configuration

You can use the platform's dynamic configuration for application settings that are loaded at runtime. You can also subscribe to changes in these settings. These may include styling options, metadata or feature toggling. Within Studio, these settings are found in the Project > Setup > Experience tab and are specified in your App Spec.
In order to use this capability, you will need to load the Project and obtain data from its fields as follows:
JavaScript
iOS
Android
async function displayProject() {
try {
const project = await getProject();
const {
id,
fields: { my_field }
} = project;
​
} catch (e) {
console.error('Something went wrong!', e);
}
}
func loadProject() {
// Interact will already be initialised at this stage
Interact.defaultCore.getProject(completion: { [weak self] result in
guard let self = self else { return }
do {
self.display(project: try result.get())
} catch {
// Treat the error
}
})
}
​
func display(project: Project) {
// You can use project fields in your UI by fetching them like so:
let id = project.id
let myField = project.fields["my_field"]
}
fun loadProject() {
Core.default!!.interact.getProject {
it.onSuccess {
display(project = it)
}
it.onFailure {
// Treat the error, `it` is a throwable
}
}
}
​
fun display(project: Project) {
// You can use project fields in your UI by fetching them like so:
val id = project.id
val myField = project.fields["my_field"]
}
You can be notified of any update on the project by using this snippet:
JavaScript
iOS
Android
// Called whe the project fields are updated
const unsubscribeOnProjectFieldsUpdated = onProjectFieldsUpdated(
project,
() => { console.log(project) }
);
​
// Called when the project listings are updated
const unsubscribeOnProjectListingsUpdated = onProjectListingsUpdated(
project,
() => { console.log(project) }
);
​
// Called when an event is published
const unsubscribeOnEventPublished = onEventPublished(
project,
(event) => { console.log(event) }
);
class MyProjectUpdateDelegate: ProjectUpdateDelegate {
func didPublishEvent(project: Project, event: Event) {
// Code when an event is published
}
​
func didRemoveEvent(project: Project, event: Event) {
// Called when an event is removed
}
​
func didUpdateProjectFields(project: Project) {
// Called when the project fields change
}
}
​
let myDelegate = MyProjectUpdateDelegate()
project.add(listener: myDelegate)
​
// When we no longer need to be notified about project changes.
project.remove(listener: myDelegate)
class MyProjectUpdateListener : ProjectUpdateListener {
override fun onEventPublished(project: Project, event: Event) {
// Code when an event is published
}
​
override fun onEventRemoved(project: Project, event: Event) {
// Called when an event is removed
}
​
override fun onProjectFieldsUpdated(project: Project) {
// Called when the project fields change
}
}
​
val myListener = MyProjectUpdateListener()
project.add(myListener)
​
// When we no longer need to be notified about project changes.
project.remove(myListener)

Localise your application

If you are supporting multiple languages, you may also want to specify which language to use in your application. You can do so through the Project using the following snippet:
JavaScript
iOS
Android
import { getProject } from "@monterosa-sdk/interact-kit";
​
const project = await getProject();
​
project.locale = 'en';
project.setCurrentLanguage("en")
project.setLocale(context = this, Locale.UK)
Read through our localisation guide to learn how to setup multiple languages in Studio

Displaying an Event

In many cases, you'll want to display a list of events for your users to select one, or at the very least you'll want to fetch the data of a single event in order to contextualise the Elements the user is seeing.
While you may not always want to process the currently active Event, this is the most common approach to selecting which Event is the focal point. The snippet below illustrates how to retrieve the list of all available Events and identify one that is currently in the active state.
You can use the state of the Event to filter and locate the Event that suits your needs. There are three states an event can be in:
  • Active: When the Event is currently live
  • Upcoming: When the Event is available, but it's start date is in the future
  • Finished: When the Event has concluded
JavaScript
iOS
Android
async function displayActiveEvent() {
try {
// If left unspecified, the `getEvents` function would use
// the project you setup in the SDK by calling `configure()`
const events = await getEvents();
​
const firstActiveEvent =
events.find(({ state }) => state === EventState.Active);
​
const {
id,
name,
endAt,
fields: {
my_field: eventCustomField,
},
} = firstActiveEvent;
​
console.log(firstActiveEvent, eventCustomField);
} catch (e) {
console.error('Something went wrong!', e);
}
}
func displayActiveEvent(in project: Project) {
// If left unspecified, the `getEvents` function would use
// the project you setup in the SDK by calling `configure()`
project.getEvents { result in
do {
let events = try result.get()
// You can find an active event by checking it's state
guard let firstActiveEvent = events.first(where: { $0.state == .active }) else {
return
}
// You can fetch some of its properties
// And display them in your UI as you see fit
let id = firstActiveEvent.id
let myField = firstActiveEvent.fields["my field"]
let eventName = firstActiveEvent.name
let eventFinishDate = firstActiveEvent.endAt
} catch {
// Treat the error
}
}
}
fun displayActiveEvent(project: Project) {
// If left unspecified, the `getEvents` function would use
// the project you setup in the SDK by calling `configure()`
project.getEvents {
it.onFailure {
// Treat the error, `it` is a throwable
}
it.onSuccess {
val firstActiveEvent = it.firstOrNull { it.state == EventState.ACTIVE }
// You can fetch some of its properties
// And display them in your UI as you see fit
val id = firstActiveEvent?.id
val myField = firstActiveEvent?.fields?.get("my field")
val eventName = firstActiveEvent?.name
val eventFinishDate = firstActiveEvent?.endAt
}
}
}
getEvents will return the list of events sorted so that the most recent event is first, and the oldest is last
Additionally, you can be notified of any updates to the Event using this snippet:
JavaScript
iOS
Android
// Called when an element is published to an event
const unsubscribeOnElementPublished = onElementPublished(event,
(element) => { console.log(element) }
);
​
// Called when an element is revoked from the event
const unsubscribeOnElementRevoked = onElementRevoked(
event,
element => { console.log(element) }
);
​
// Called when the event is updated
const unsubscribeOnEventUpdated = onEventUpdated(
event,
() => { console.log(event) }
);
​
// Called when the event state changes
const unsubscribeOnEventState = onEventState(
event,
(state) => { console.log(state) }
);
class MyEventUpdateDelegate: EventUpdateDelegate {
func didReceiveUpdate(event: Event) {
// Called when the data in the event changes
}
func didChangeState(event: Event) {
// Called when the state of the event changes
}
func didPublishElement(event: Event, element: Element) {
// Called when an element is published
}
func didRevokeElement(event: Event, element: Element) {
// Called when an element is revoked
}
}
​
let myDelegate = MyEventUpdateDelegate()
event.add(listener: myDelegate)
​
// When we no longer need to be notified about event changes.
event.remove(listener: myDelegate)
class MyEventUpdateListener : EventUpdateListener {
override fun onEventUpdated(event: Event) {
// Called when the data in the event changes
}
​
override fun onEventStateChanged(event: Event) {
// Called when the state of the event changes
}
​
override fun onElementPublished(event: Event, element: Element) {
// Called when an element is published
}
​
override fun onElementRevoked(event: Event, element: Element) {
// Called when an element is revoked
}
}
​
val myListener = MyEventUpdateListener()
event.add(myListener)
​
// When we no longer need to be notified about event changes.
event.remove(myListener)
Alternatively, you can also obtain the Event by its ID. This is useful if you want to attach a given known Event to specific information in your platform. For instance, you could create an Event for a given football match, and then link all the articles relevant to that match to the Event, so that you display match details, or interactive Elements relevant to that match within the article.
The following snippet showcases how to get an Event from an ID, which we'll assume in this case is being provided by your API.
JavaScript
iOS
Android
import { getEvent } from "@monterosa-sdk/interact-kit";
​
const event = await getEvent('<event-id>'); // can be null
let event = project.getEvent(byId: '<event-id>') // can be null
project.getEvent('<event-id>') { result ->
result.onSuccess { event ->
//event found
}
result.onFailure {
//event not found
}
}

Displaying Elements

Within an Event, content creators will be publishing Elements – bi-directional content units that have certain properties and behaviours built in, as defined in the App Spec. In general, there's two types of Elements, interactive Elements, that allow your users to interact with the content by providing answers, and seeing how other people have responded, and non Interactive Elements.
For example, you can define a non interactive Element to be an information unit, like a blog post, a message, or a link to embed. Meanwhile you can define an interactive Element to behave like a poll, containing a question, a number of possible answer options and a duration.
An Event may include multiple Elements. For example if you create an Event for a soccer game, an Element might be a result prediction appearing before the game starts and another that triggers whenever a goal is scored.

Non Interactive Elements

We'll first start by showcasing how to use non interactive Elements in your application.
The snippet below retrieves the array of Elements already existing within the Event and illustrates how you can use its contentType to differentiate each Element type. In the example, we determine a single type of Element being received - goalScored.
JavaScript
iOS
Android
async function displayElements(event) {
try {
const elements = await getElements(event);
​
for (const element of elements) {
switch (element.contentType) {
case 'goalScored':
displayGoalScored(element);
break;
}
}
} catch (e) {
console.error('Something went wrong!', e);
}
}
​
function displayGoalScored(element) {
// In this function we know the element is a goal scored, so we can
// equally make some assumptions about what data will be available.
// As you can see below, given the control you have over the App
// Spec, you can provide via Studio as much data as you want to support,
// in this example the goal scorer name, number, and the amount of goals
// they scored today, so you can add some extra fanfare
// in your UI when they score a hat trick!
const {
fields: {
goalScorerName,
goalScorerNumber,
goalScorerGoalsToday,
},
} = element
// Draw the UI based on your UI framework.
}
func displayElements(in event: Event) {
event.getElements { [weak self] result in
guard let self = self else { return }
do {
let elements = try result.get()
elements.forEach { element in
switch element.contentType {
case "goalScored":
self.displayGoalScored(element)
default:
// Element type not recognised.
return
}
}
} catch {
// Treat the error
}
}
}
​
func displayGoalScored(_ element: Element) {
// In this function we know the element is a goal scored, so we can
// equally make some assumptions about what data will be available.
// As you can see below, given the control you have over the App
// Spec, you can provide via Studio as much data as you want to support,
// in this example the goal scorer name, number, and the amount of goals
// they scored today, so you can add some extra fanfare
// in your UI when they score a hat trick!
let goalScorerName = element.fields["goalScorerName"]
let goalScorerNumber = element.fields["goalScorerNumber"]
let goalScorerGoalsToday = element.fields["goalScorerGoalsToday"]
// Draw the UI based on your UI framework.
}
fun displayElements(event: Event) {
event.getElements {
it.onFailure {
// Treat the error, `it` is a throwable
}
it.onSuccess {
it.forEach { element ->
when (element.contentType) {
"goalScored" -> displayGoalScored(element)
else -> {
// element type not recognised
}
}
}
}
}
}
​
fun displayGoalScored(element: Element) {
// In this function we know the element is a goal scored, so we can
// equally make some assumptions about what data will be available.
// As you can see below, given the control you have over the App
// Spec, you can provide via Studio as much data as you want to support,
// in this example the goal scorer name, number, and the amount of goals
// they scored today, so you can add some extra fanfare
// in your UI when they score a hat trick!
val goalScorerName = element.fields["goalScorerName"]
val goalScorerNumber = element.fields["goalScorerNumber"]
val goalScorerGoalsToday = element.fields["goalScorerGoalsToday"]
// Draw the UI based on your UI framework.
}
getElements will return a list of elements sorted so that the most recent element is first, and the oldest is last.
Additionally, you can subscribe to updates to a given Element using the following snippet:
JavaScript
iOS
Android
// Called when the results of an interactive element change
const unsubscribeOnElementResults = onElementResults(
element,
(results) => { console.log(results) }
);
​
// Called when the element is updated
const unsubscribeOnElementUpdated = onElementUpdated(
element,
() => { console.log(element) }
);
​
// Called when the state of the element is updated
const unsubscribeOnElementStateChanged = onElementStateChanged(
element,
() => { console.log(element) }
);
class MyElementUpdateDelegate: ElementUpdateDelegate {
func didChangeState(element: Element) {
// Called when the element state is updated
}
​
func didReceiveResults(element: Element) {
// Called when the results of the element are updated
}
​
func didReceiveUpdate(element: Element) {
// Called when the element is updated
}
}
​
​
let myElementUpdateDelegate = MyElementUpdateDelegate()
element.add(listener: myElementUpdateDelegate)
​
// When we no longer need to be notified about element changes.
element.remove(listener: myElementUpdateDelegate)
class MyElementUpdateListener : ElementUpdateListener {
override fun onElementStateChanged(element: Element) {
// Called when the element state is updated
}
​
override fun onElementResults(element: Element) {
// Called when the results of the element are updated
}
​
override fun onElementUpdated(element: Element) {
// Called when the element is updated
}
​
}
​
val myListener = MyElementUpdateListener()
element.add(myListener)
​
// When we no longer need to be notified about element changes.
element.remove(myListener)

Interactive Elements

Interactive Elements get fans involved and make your experiences more rewarding. They have the following properties, which extend non-interactive Elements:
  • State: open or closed state, where open means the user can still interact with the Element. The timespan where the user can vote can be obtained through the duration property.
  • Question and AnswerOptions: The Element usually will have a question associated with it for the user to answer by interacting with some potential answers. Through the App Spec you can specify what data is included in either the Question and AnswerOptions. This enables you to create rich questions and answers which could include videos, images, links to other content on your application, ...
  • Results: Results bring a sense of belonging into your users interaction, by letting your users know how their peers are answering a question. You will receive these values both as a total vote count as well as a percentage of the total votes.
The snippet below updates the previous one to add a new type of element, a poll:
JavaScript
iOS
Android
async function displayElements(event) {
try {
const elements = await getElements(event);
​
for (const element of elements) {
switch (element.contentType) {
case 'poll':
displayPoll(element);
break;
case 'goalScored':
displayGoalScored(element);
break;
}
}
} catch (e) {
console.error('Something went wrong!', e);
}
}
​
function displayPoll(element) {
const {
question: {
text: questionText,
imageURL: questionImageURL,
},
answerOptions,
state,
fields: {
poll_custom_field: pollCustomField,
}
} = element;
const answers = answerOptions.map(({ text }) => text);
// Draw the poll
}
func displayElements(in event: Event) {
event.getElements { [weak self] result in
guard let self = self else { return }
do {
let elements = try result.get()
elements.forEach { element in
switch element.contentType {
case "poll":
self.displayPoll(element)
case "goalScored":
self.displayGoalScored(element)
default:
// Element type not recognised.
return
}
}
} catch {
// Treat the error
}
}
}
​
func displayPoll(_ element: Element) {
let question = element.question!["text"]
let questionImageURL = element.question!["imageURL"]
let answers = element.answerOptions!.map { answerOption in
return answerOption["text"] as! String
}
let pollCustomField = element.fields["poll custom field"]
let state = element.state
// Draw the poll
}
fun displayElements(event: Event) {
event.getElements {
it.onFailure {
// Treat the error, `it` is a throwable
}
it.onSuccess {
it.forEach { element ->
when (element.contentType) {
"poll" -> displayPoll(element)
"goalScored" -> displayGoalScored(element)
else -> {
// element type not recognised
}
}
}
}
}
}
​
fun displayPoll(element: Element) {
val question = element.question!!["text"]
val questionImageURL = element.question!!["imageURL"]
​
val answers = element.answerOptions!!.map {
it["text"]
}
​
val pollCustomField = element.fields["poll custom field"]
val state = element.state;
// Draw the poll
}

Answering an Interactive Element

Once you have displayed the answer options on screen, submit the user's answer using the answer()method.
In the snippet below we show how an answer can be submitted, alongside its error handling so you can contextualise to the user if anything goes wrong. We assume that the variable userAnswer contains the 0-based index of the answer option selected by the user.
JavaScript
iOS
Android
function sendAnswer(element, index) {
try {
// index should be e.g. 0 to the count of options available - 1
answer(element, index);
// Your answer was sent successfully
} catch {
if (e instanceof MonterosaError) {
switch (e.code) {
case AnswerError.OptionIndexOutOfRange:
// The index is outside the range of possible options
break;
case AnswerError.AboveMaxVoteOptions:
// You voted for more indexes than is allowed
break;
case AnswerError.BelowMinVoteOptions:
// You voted for fewer indexes than is allowed
break;
case AnswerError.AboveMaxVotesPerUser:
// You voted with a higher total value than is allowed
break;
case AnswerError.AboveMaxVotesPerOption:
// You voted with a higher value than is allowed in a single option
break;
case AnswerError.VotedOnNonInteractiveElement:
// You tried to vote on a non interactive element
break;
case AnswerError.VotedOnClosedElement:
// You voted on closed element
break;
default:
// Shouldn't occur, but be ready for it as more cases could be added in the future.
break;
}
} else {
// Shouldn't occur
}
}
}
func answer(element: Element, with index: Int) {
do {
try element.answer(with: index)
// Your answer was sent successfully
}
catch let err as Element.AnswerError where err == .optionIndexOutOfRange {
// The index is outside the range of possible options
}
catch let err as Element.AnswerError where err == .aboveMaxVoteOptions {
// You voted for more indexes than is allowed
}