# MBurger Engagement Platform 🍔

## Welcome to the MBurger official Engagement Platform documentation

{% hint style="success" %}
Here you will learn everything you need to know about MBurger Engagement Platform and how to use it at its best!
{% endhint %}

{% content-ref url="/pages/-MDololcuWvN0n5JIsuK" %}
[  iOS Docs](/ios-docs/messages)
{% endcontent-ref %}

{% content-ref url="/pages/-ME7zF2oeRoFU502ZHnV" %}
[Android Docs](/android-docs/messages)
{% endcontent-ref %}


# Messages

## MBMessagesSwift

MBMessagesSwift is a plugin libary for [MBurger](https://mburger.cloud), that lets you display in app messages and manage push notifications in your app. The minimum deployment target for the library is iOS 11.0.

Using this library you can display the messages that you set up in the MBurger dashboard in your app. You can also setup and manage push notifications connected to your MBurger project.


# Installation

### Swift Package Manager

With Xcode 11 you can start using [Swift Package Manager](https://swift.org/package-manager/) to add **MBMessagesSwift** to your project. Follow those simple steps:

* In Xcode go to File > Swift Packages > Add Package Dependency.
* Enter `https://github.com/Mumble-SRL/MBMessagesSwift.git` in the "Choose Package Repository" dialog and press Next.
* Specify the version using rule "Up to Next Major" with "0.1.1" as its earliest version and press Next.
* Xcode will try to resolving the version, after this, you can choose the `MBMessagesSwift` library and add it to your app target.

### CocoaPods

CocoaPods is a dependency manager for iOS, which automates and simplifies the process of using 3rd-party libraries in your projects. You can install CocoaPods with the following command:

```ruby
$ gem install cocoapods
```

To integrate the MBMessagesSwift into your Xcode project using CocoaPods, specify it in your Podfile:

```ruby
platform :ios, '12.0'

target 'TargetName' do
    pod 'MBMessagesSwift'
end
```

If you use Swift rememember to add `use_frameworks!` before the pod declaration.

Then, run the following command:

```
$ pod install
```

CocoaPods is the preferred methot to install the library.

### Carthage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate MBMessagesSwift into your Xcode project using Carthage, specify it in your Cartfile:

```
github "Mumble-SRL/MBMessagesSwift"
```

### Manual installation

To install the library manually drag and drop the folder `MBMessages` to your project structure in XCode.

Note that `MBMessagesSwift` has `MBurgerSwift (1.0.8)` and `MPushSwift (0.2.13)` as dependencies, so you have to install also those libraries.


# Initialization

To initialize the SDK you have to add `MBMessagesSwift` to the array of plugins of `MBurger`.

```swift
import MBurgerSwift
import MBMessagesSwift

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    MBManager.shared.apiToken = "YOUR_API_TOKEN"
    MBManager.shared.plugins = [MBMessages()]

    return true
}
```

Then you have to tell MBManager.shared that the app has been opened with `MBManager.shared.applicationDidFinishLaunchingWithOptions(launchOptions: launchOptions)`, this will trigger all the startup actions of the MBurger plugins. Once you've done this in app messages will be fetched automatically at the startup of the application and showed, if they need to be showed.

```swift
...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    MBManager.shared.apiToken = "YOUR_API_TOKEN"
    MBManager.shared.plugins = [MBMessages()]

    MBManager.shared.applicationDidFinishLaunchingWithOptions(launchOptions: launchOptions)

    return true
}
```

### Initialize MBMessages with parameters

You can set a couples of parameters when initializing the `MBMessages` plugin:

```swift
let messagesPlugin = MBMessages(delegate: [the delegate],
                                viewDelegate: [view delegate],
                                styleDelegate: [style delegate],
                                messagesDelay: 1
                                debug: true)
```

* **messagesDelay**: it's the time after which the messages will be displayed once fetched
* **debug**: if this is set to `true`, all the message returned by the server will be displayed, if this is set to `false` a message will appear only once for app installation. This is `false` by default
* **delegate**: the delegate will receive a call if the fetch of the messages fails, with the error that caused the fail, see MBMessagesDelegate for more details.
* **viewDelegate**: the view delegates will receive calls when views of messages are showed or hidden, it will also receives a call when the button of the views will be touched, so you need to implement this protocol if you want to open an in-app link from an in app message. See MBInAppMessageViewDelegate for a detailed description of the protocol.
* **styleDelegate**: you can use this protocol to specify colors and fonts of the in app messages. See Stylize in app messages for more details

## Automation

If messages have automation enabled they will be ignored and managed by the [MBAutomationSwift SDK](https://github.com/Mumble-SRL/MBAutomationSwift.git) so make sure to include and configure the automation SDK correctly.


# Push notifications

With this plugin you can also manage the push notification section of MBurger, this is a wrapper around MPush, the underlying platform, so you should refer to the [MPush documentation ](https://github.com/Mumble-SRL/MPush-Swift) to understand the concepts and to start the push integration. In order to use `MBMessagesSwift` instead of `MPushSwift` you have to do the following changes:

Set the push token like this:

```swift
MBMessages.pushToken = "YOUR_PUSH_TOKEN"
```

And then register your device to topics (all the other function have a similar syntax change):

```swift
MBMessages.registerDeviceToPush(deviceToken: deviceToken, success: {
    MBMessages.registerPushMessages(toTopic: MBPTopic("YOUR_TOPIC"))
})
```

MBurger has 2 default topics that you should use in order to guarantee the correct functtionality of the engagement platform:

* `MBMessages.projectPushTopic`: this topic represents all devices registred to push notifications for this project
* `MBMessages.devicePushTopic`: this topic represents the current device

```swift
MBMessages.registerPushMessages(toTopics:[MBMessages.projectPushTopic,
                                          MBMessages.devicePushTopic,
                                          MBPTopic("OTHER_TOPIC")])
```

#### MBPTopic additional parameters

When creating topic you can specify additional parameters:

* `title`: a title fot that topic that will be displayed in the dashboard, if not specified it has the same value as the topic id
* `single`: If the topic identify a single user or a group of users, defaults to `false`

## User interaction with a push

With `MBMessagesSwift` you can setup a callback that will be called when the user interacts with a push notification or opens the app from a push. You can setup the code like this, the payload variable will be the payload of the push:

```swift
MBMessages.userDidInteractWithNotificationBlock = { payload in
    // Do actions in response
    print("Notification arrived:\n\(payload)")
}
```

In order to this to function you will have to tell `MBMessagesSwift` that a notification has arrived so you need to add this in those lines in your `UNUserNotificationCenterDelegate` class, often the `AppDelegate`.

```swift
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler
    completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Add this line
    MBMessages.userNotificationCenter(willPresent: notification)
    completionHandler(UNNotificationPresentationOptions.alert)
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler
    completionHandler: @escaping () -> Void) {
    // Add this line
    MBMessages.userNotificationCenter(didReceive: response)
    completionHandler()
}
```


# Rich Notifications

From MBurger you can send medias (images/videos/audio) with a push notification. The link of the media will be sent in the payload of the notifications in the `media_url` field. To view the media sent in the notifications follow tihs steps. &#x20;

### 1. Create a Notification Service target

In Xcode go to File -> New Target and choose [Notification Service Extension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension)

. This will create a class that will intercept all push notification sent to the app, you will be able to change its content from this class.

![](/files/-MIT6usGhij0mGZOzgVg)

### 2. Download the media

In the notification service class use this code to download the media and attach to the push notification.

```swift
class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            if let mediaUrl = request.content.userInfo["media_url"] as? String, let fileUrl = URL(string: mediaUrl) {
                let type = request.content.userInfo["media_type"] as? String
                downloadMedia(fileUrl: fileUrl, type: type, request: request, bestAttemptContent: bestAttemptContent) {
                    contentHandler(bestAttemptContent)
                }
            } else {
                contentHandler(bestAttemptContent)
            }
        }
    }
    
    func downloadMedia(fileUrl: URL, type: String?, request: UNNotificationRequest, bestAttemptContent: UNMutableNotificationContent, completion: @escaping () -> Void) {
        let task = URLSession.shared.downloadTask(with: fileUrl) { (location, _, _) in
            if let location = location {
                let tmpDirectory = NSTemporaryDirectory()
                let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
                let tmpUrl = URL(string: tmpFile)!
                do {
                    try FileManager.default.moveItem(at: location, to: tmpUrl)
                    
                    var options: [String: String]? = nil
                    if let type = type {
                        options = [String: String]()
                        options?[UNNotificationAttachmentOptionsTypeHintKey] = type
                    }
                    if let attachment = try? UNNotificationAttachment(identifier: "media." + fileUrl.pathExtension, url: tmpUrl, options: options) {
                        bestAttemptContent.attachments = [attachment]
                    }
                    completion()
                } catch {
                    completion()
                }
            }
        }
        task.resume()
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}
```


# Stylize in app messages

If you want to specify fonts and colors of the messages displayed you can use the `MBInAppMessageViewStyleDelegate` protocol. All the functions of the protocol are optional, if a function is not implemented the framework will use a default value. The elements that can be stylized are the following:

* **backgroundStyle**: can be a solid color or a translucent color
* **backgroundColor**: the color of the background
* **titleColor**: the text color for the title of the message
* **bodyColor**: the text color for the body
* **closeButtonColor**: the color of the close button
* **button1BackgroundColor**: the background color of the first action button
* **button1TitleColor**: the text color of the first action button
* **button2BackgroundColor**: the background color of the second action button
* **button2TitleColor**: the text color of the second action button
* **button2BorderColor**: the border color of the second action button
* **titleFont**: the font of the title
* **bodyFont**: the font of the body
* **buttonsTextFont**: the font of the buttons titles

Example:

```swift
func backgroundStyle(forMessage message: MBInAppMessage) -> MBInAppMessageViewBackgroundStyle {
    return .solid
}

func backgroundColor(forMessage message: MBInAppMessage) -> UIColor {
    return .green
}

func titleColor(forMessage message: MBInAppMessage) -> UIColor {
    return .blue
}

func bodyColor(forMessage message: MBInAppMessage) -> UIColor {
    return .darkText
}

func button1TitleColor(forMessage message: MBInAppMessage) -> UIColor {
    return .white
}

func button1BackgroundColor(forMessage message: MBInAppMessage) -> UIColor {
    return .cyan
}
```


# Message Metrics

Using `MBMessagesSwift` gives you also the chanche to collect informations about your user and the push, those will be displyed on the [MBurger](https://mburger.cloud) dashboard. As described in the prervious paragraph, in order for this to function, you have to tell `MBMessagesSwift` that a push has arrived, if you've already done it in the step above you're fine, otherwise you need to add `MBMessages.userNotificationCenter(willPresent: notification)` and `MBMessages.userNotificationCenter(didReceive: response)` to your `UNUserNotificationCenterDelegate` class.


# Audience

## MBAudienceSwift

MBAudienceSwift is a plugin libary for [MBurger](https://mburger.cloud), that lets you track user data and behavior inside your and to target messages only to specific users or groups of users. This plugin is often used with the [MBMessagesSwift](https://github.com/Mumble-SRL/MBMessagesSwift) plugin to being able to send push and messages only to targeted users.


# Installation

### Swift Package Manager

With Xcode 11 you can start using [Swift Package Manager](https://swift.org/package-manager/) to add **MBAudienceSwift** to your project. Follow those simple steps:

* In Xcode go to File > Swift Packages > Add Package Dependency.
* Enter `https://github.com/Mumble-SRL/MBAudienceSwift.git` in the "Choose Package Repository" dialog and press Next.
* Specify the version using rule "Up to Next Major" with "1.0.1" as its earliest version and press Next.
* Xcode will try to resolving the version, after this, you can choose the `MBAudienceSwift` library and add it to your app target.

## CocoaPods

CocoaPods is a dependency manager for iOS, which automates and simplifies the process of using 3rd-party libraries in your projects. You can install CocoaPods with the following command:

```ruby
$ gem install cocoapods
```

To integrate the MBurgerSwift into your Xcode project using CocoaPods, specify it in your Podfile:

```ruby
platform :ios, '12.0'

target 'TargetName' do
    pod 'MBAudienceSwift'
end
```

If you use Swift rememember to add `use_frameworks!` before the pod declaration.

Then, run the following command:

```
$ pod install
```

CocoaPods is the preferred methot to install the library.

### Chartage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate MBudienceSwift into your Xcode project using Carthage, specify it in your Cartfile:

```
github "Mumble-SRL/MBAudienceSwift"
```

## Manual installation

To install the library manually drag and drop the folder `MBAudienceSwift` to your project structure in XCode.

Note that `MBAudienceSwift` has `MBurgerSwift (1.0.5)` and `MPushSwift (0.2.12)` as dependencies, so you have to install also those libraries.


# Initialization

To initialize the SDK you have to add `MBAudience` to the array of plugins of `MBurger`.

```swift
import MBurgerSwift
import MBMessagesSwift

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    MBManager.shared.apiToken = "YOUR_API_TOKEN"
    MBManager.shared.plugins = [MBAudience()]

    return true
}
```

You can set a delegate when initializing the `MBAudience` plugin, the delegate will be called when audience data are sent successfully to the sever or if the sync fails

```swift
let audiencePlugin = MBAudience(delegate: [the delegate])
```


# Tracked data

Below are described all the data that are tracked by the MBAudience SDK and that you will be able to use from the [MBurger](https://mburger.cloud) dashboard. Most of the data are tracked automatically, for a couples a little setup by the app is neccessary.

* **app\_version**: The current version of the app.
* **locale**: The locale of the phone, the value returned by `Locale.preferredLanguages.first`.
* **sessions**: An incremental number indicating the number of time the user opens the app, this number is incremented at each startup.
* **sessions\_time**: The total time the user has been on the app, this time is paused when the app goes in background (using `didEnterBackgroundNotification`) .and it's resumed when the app re-become active (using `willEnterForegroundNotification`).
* **last\_session**: The start date of the last session.
* **push\_enabled**: If push notifications are enabled or not; to determine this value the framework uses this function: `UNUserNotificationCenter.current().getNotificationSettings`.
* **location\_enabled**: If user has given permissions to use location data or not; this is true if `CLLocationManager.authorizationStatus()` is `authorizedAlways` or `authorizedWhenInUse`.
* **mobile\_user\_id**: The user id of the user curently logged in MBurger
* **custom\_id**: A custom id that can be used to filter further.
* **tags**: An array of tags
* **latitude, longitude**: The latitude and longitude of the last place visited by this device


# Tags

You can set tags to assign to a user/device (e.g. if user has done an action set a tag), so you can target those users later:

To set a tag:

```swift
MBAudience.setTag("TAG", value: "VALUE")
```

To remove it:

```swift
MBAudience.removeTag("TAG")
```


# Identify a user

## Custom Id

You can set a custom id in order to track/target users with id coming from different platforms.

To set a custom id:

```swift
MBAudience.setCustomId("CUSTOM_ID")
```

To remove it:

```swift
MBAudience.removeCustomId()
```

To retrieve the current saved id:

```swift
MBAudience.getCustomId()
```

## Mobile User Id

This is the id of the user currently logged in MBurger using MBAuth. At the moment the mobile user id is not sent automatically when a user log in/log out with MBAuth. It will be implemented in the future but at the moment you have to set and remove it manually when the user completes the login flow and when he logs out.

To set the mobile user id:

```swift
MBAudience.setMobileUserId(MOBILE_USER_ID)
```

To remove it, if the user logs out:

```swift
MBAudience.removeMobileUserId()
```

To get the currently saved mobile user id:

```swift
MBAudience.getMobileUserId()
```


# Location

MBAudience let you track and target user based on their location, the framework uses the method [startMonitoringSignificantLocationChanges](https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati) of the CoreLocation manager with an accuracy of `kCLLocationAccuracyHundredMeters`. To start monitoring for location changes call, it will continue monitoring until the stop method is called:

```swift
MBAudience.startLocationUpdates()
```

To stop monitoring location changes you have to call:

```swift
MBAudience.stopLocationUpdates()
```


# Automation

## MBAutomationSwift

`MBAutomationSwift` is a plugin libary for [MBurger](https://mburger.cloud), that lets you send automatic push notifications and in-app messages crated from the MBurger platform. It has as dependencies [MBMessagesSwift](https://github.com/Mumble-SRL/MBMessagesSwift) and [MBAudienceSwift](https://github.com/Mumble-SRL/MBAudienceSwift). With this library you can also track user events and views.

Using `MBAutomationSwift` you can setup triggers for in-app messages and push notifications, in the MBurger dashboard and the SDK will show the coontent automatically when triggers are satisfied.

It depends on `MBAudienceSwift` because messages can be triggered by location changes or tag changes, coming from this SDK.

It depends on `MBMessagesSwift` because it contains all the views for the in-app messages and the checks if a message has been already displayed or not.

The data flow from all the SDKs is manage entirely by MBurger, yuo don't have to worry about it.


# Installation

### Swift Package Manager

With Xcode 11 you can start using [Swift Package Manager](https://swift.org/package-manager/) to add **MBAutomationSwift** to your project. Follow those simple steps:

* In Xcode go to File > Swift Packages > Add Package Dependency.
* Enter `https://github.com/Mumble-SRL/MBAutomationSwift.git` in the "Choose Package Repository" dialog and press Next.
* Specify the version using rule "Up to Next Major" with "1.0.1" as its earliest version and press Next.
* Xcode will try to resolving the version, after this, you can choose the `MBAutomationSwift` library and add it to your app target.

## CocoaPods

CocoaPods is a dependency manager for iOS, which automates and simplifies the process of using 3rd-party libraries in your projects. You can install CocoaPods with the following command:

```ruby
$ gem install cocoapods
```

To integrate the MBurgerSwift into your Xcode project using CocoaPods, specify it in your Podfile:

```ruby
platform :ios, '12.0'

target 'TargetName' do
    pod 'MBAutomationSwift'
end
```

If you use Swift rememember to add `use_frameworks!` before the pod declaration.

Then, run the following command:

```
$ pod install
```

CocoaPods is the preferred methot to install the library.

### Chartage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate MBudienceSwift into your Xcode project using Carthage, specify it in your Cartfile:

```
github "Mumble-SRL/MBAutomationSwift"
```

## Manual installation

To install the library manually drag and drop the folder `MBAutomationSwift` to your project structure in XCode.

Note that `MBAutomationSwift` has `MBurgerSwift`, `MBMessagesSwift` and `MBAudienceSwift` as dependencies, so you have to install also those libraries manually.


# Initialization

To initialize automation you need to insert `MBAutomation` as a `MBurger` plugins, tipically automation is used in conjunction with the `MBMessagesSwift` and `MBAudienceSwift` plugins.

```swift
MBManager.shared.plugins = [MBAutomation(), ... other plugins]
```

MBAutomation can bbe initialized with 3 optional parameters:

* `trackingEnabled`: If the tracking is enabled or not, setting this to false all the tracking will be disabled
* `trackViewsAutomatically`: If the automatic track of views is enabled or not
* `eventsTimerTime`: The frequency used to send events and view to MBurger


# Triggers

Every in-appmessage or push notification coming from MBurger can have an array of triggers, those are managed entirely by the MBAutomation SDK that evaluates them and show the mssage only when the conditioon defined by the triggers are matched.

If thre are more than one trigger, they can be evaluated with 2 methods:

* `any`: once one of triggers becomes true the message is displayed to the user
* `all`: all triggers needs to be true in order to show the message.

Here's the list of triggers managed by automation SDK:

**App opening**

`MBAppOpeningTrigger`: Becoomes true when the app has been opened n times (`times` property), it's checked at the app startup.

**Event**

`MBEventTrigger`: Becomes true when an event happens n times (`times` property)

**Inactive user**

`MBInactiveUserTrigger`: Becomes true if a user has not opened the app for n days (`days` parameter)

**Location**

`MBLocationTrigger`: If a user enters a location, specified by `latitude`, `longitude` and `radius`. This trigger can be activated with a day delay defined as the `afterDays` property. The location data comes from the [MBAudienceSwift](https://github.com/Mumble-SRL/MBAudienceSwift) SDK.

**Tag change**

`MBTagChangeTrigger`: If a tag of the [MBAudienceSwift](https://github.com/Mumble-SRL/MBAudienceSwift) SDK changes and become equals or not to a value. It has a `tag` property (the tag that needs to be checked) and a `value` property (the value that needs to be equal or different in order to activate the trigger)

**View**

`MBViewTrigger`: it's activated when a user enters a view n times (`times` property). If the `secondsOnView` the user needs to stay the seconds defined in order to activate the trigger.


# Send events

You can send events with the `MBAutomationSwift` like this:

```swift
MBAutomation.sendEvent("event")
```

You can specify 2 more parameters, both optional: `name` a name that will be displayed in the MBurger dashboard and a dictionary of additional `metadata` to specify more fields of the event

```swift
MBAutomation.sendEvent("purchase",
                       name: "Purchase",
                       metadata: ["quantity": 1])
```

Events are saved in a local database and sent to the server every 10 seconds, you can change the frequency setting the `eventsTimerTime` property.


# View Tracking

In MBAutomation the tracking of the views is automatic, you can disable it initializing `MBAutomation` with `trackViewsAutomatically` to `false`. `MBAutomation` uses [method swizzling](https://nshipster.com/method-swizzling/) to track view automatically on `viewDidAppear`.

The default name for all the ViewControllers is the class name (e.g. if your ViewController is called HomeViewController you will see HomeViewController as the view). If you want to change the name for a ViewController you can setup the `mbaTrackingName` of the ViewController.

```swift
import MBAutomationSwift

override func viewDidLoad() {
    super.viewDidLoad()
     ...

    mbaTrackingName = "Home"
    ...
}
```

You can send additional data with the view event setting the `mbaTrackingMetadata` property of the ViewController, those will be displayed in the metadata field of the dashboard.

If you have diisabled the automatic tracking and you still want to track the views you can use this function, passing a `UIViewController`.

```swift
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    MBAutomation.trackScreenView(self)
}
```

As the events, views are saved in a local database and sent to the server every 10 seconds and you can change the frequency setting the `eventsTimerTime` property.


# Messages

MBMessages is a plugin library for [MBurger](https://mburger.cloud/), lets you display in app messages and manage push notifications in your app. The minimum deployment target for the library is 4.2 (API 17).

Using this library you can display the messages that you set up in the MBurger dashboard in your app. You can also setup and manage push notifications connected to your MBurger project.


# Prerequisites for Push Notifications

MBurger Engagement platform uses **FCM** (Firebase Cloud Messaging) so send push notifications. If you wish to add this feature to your app you should before follow these steps regarding FCM configuration:&#x20;

* Create a Firebase project by visiting [this page](https://console.firebase.google.com/) and clicking on "Add Project"
* Inside the project create your Android app by clicking "Add App" and follow the instructions, resulting in downloading a .json configuration file to move in your app folder.
* Go to the project settings clicking on the gear on the left-top part of the page:

![](/files/-MTui_5AcvaDd_rCuMEt)

* On the Settings page click on "Cloud Messaging" and copy the "Server Key" you see right below the tab

![](/files/-MTujak0iHb9MBugPySt)

* Paste the token on MBurger Engagement Platform Settings FCM box and click "Update"

![](/files/-MTukWYDlXl72BlujAWW)

* Done!


# Installation

#### Installation with gradle

This plugin only works with the latest Kotlin version of MBurger Client SDK so make sure to ad Kotlin Android Studio plugin and Kotlin dependencies to your Android project.

Add this repository to your project level `build.gradle` file under allprojects:

```
maven { url "https://dl.bintray.com/mumbleideas/MBurger-Android/" }
```

Then add **MBurger Kotlin** dependency to your `app build.gradle` file:

```
implementation 'mumble.mburger:android_kt:0.5.5'
```

Lastly add `MBMessages` library:

```
implementation 'mumble.mburger:mbmessages-android:0.4.15'
```


# Initialization

To initialize MBMessages you need to add `MBMessages` to the array of plugins of `MBurger`.

```
val plugins = ArrayList<MBPlugin>()
val plugin = MBMessages()
plugins.add(plugin)

MBurger.initialize(applicationContext, "MBURGER_KEY", false, plugins)
```

Then you need to say MBurger to initialize the plugins with the in initPlugins method from MBurger class. If you wish you can add a listener to know when the plugin have been initialized.

```
val listener: MBMessagesPluginInitialized
plugin.initListener = listener

override fun onInitialized() {
   //Plugin has been initialized correctly, can be started
}

override fun onInitializedError(error: String?) {
   //Error during initialization of MBMessages plugin
}
```

Once you've done this ask MBurger to start plugins in your main activity (be aware that it has to be an `AppCompatActivity`), then, in app messages will be fetched automatically and showed, if they need to be showed.

```
MBurger.startPlugins(activity)
```


# Stylization and parameters

You can set a couples of parameters when creating the plugin object:

* **order**: which order to be initialized this plugin, if not set plugin will be initialized according to the plugin array order
* **delayInSeconds**: it's the time after which the messages will be displayed once fetched

The `MBMessagesManager` is the main class which shows the messages and handles the stylization and if messages need to be shown or not. There are many possible parameters you can set to change message appaerances:

* **forceMessageStyle**: change the style for the messages:
  * **MBIAMConstants**.IAM\_STYLE\_BANNER\_TOP
  * **MBIAMConstants**.IAM\_STYLE\_BANNER\_BOTTOM
  * **MBIAMConstants**.IAM\_STYLE\_BANNER\_CENTER
  * **MBIAMConstants**.IAM\_STYLE\_FULL\_SCREEN\_IMAGE
* **debug**: show messages even if they have been already shown
* **backgroundColor**: the color of the background
* **titleColor**: the text color for the title of the message
* **bodyColor**: the text color for the body
* **closeButtonColor**: the color of the close button
* **closeButtonBackgroundColor**: the background color of the close button round
* **button1BackgroundColor**: the background color of the first action button
* **button1TitleColor**: the text color of the first action button
* **button2BackgroundColor**: the background color of the second action button
* **button2TitleColor**: the text color of the second action button
* **titleFontRes**: the font resource of the title
* **bodyFontRes**: the font resource of the body
* **buttonsTextFontRes**: the font resource of the buttons titles
* **titleSizeRes**: the font size resource of the title
* **bodySizeRes**: the font size resource of the body
* **buttonsSizeRes**: the font size resource of the buttons titles

All web links will be automatically handled, the in-app messages must be handled adding the `MNBIAMClickListener` which calls `onCTAClicked` with the CTA object in order to be handled.


# Push notifications

With this plugin you can also manage the push notification section of MBurger, this is a wrapper around MPush, the underlying platform, so you should refer to the MPush documentation to understand the concepts and to start the push integration.


# Message Metrics

Using `MBMessages` gives you also the chanche to collect informations about your user and the push, those will be displyed on the [MBurger](https://mburger.cloud/) dashboard. As described in the prervious paragraph, in order for this to function, you need to configure push notification receivement as described below:

The push service must extend `MBurgerFBMessagingService` instead of `FirebaseMessagingService`, then implement this method which is a wrapper around the standard `onMessageReceived` for Firebase:

```
override fun onMBMessageReceived(remoteMessage: RemoteMessage, intent: Intent) {
}
```

Then when you create your notification to create the PendingIntent you should use the Intent provided with this function, you can add more extras or set which class you wish to set the Intent.

```
intent.setClass(applicationContext, MainActivity::class.java)
intent.putExtra("param", some_parameter)
```

Then when you call the `notify` method to show the notification call this API:

```
MBMessagesMetrics.trackShowPush(applicationContext, intent)
```

Lastly on the activity you use to call from the notification (mainly your `android.intent.action.MAIN` and `android.intent.category.LAUNCHER activity`) call this API on the onCreate method:

```
MBMessagesMetrics.checkOpenedFromPush(applicationContext, getIntent())
```


# Audience

&#x20;MBAudience is a plugin libary for [MBurger](https://mburger.cloud/), that lets you track user data and behavior inside your and to target messages only to specific users or groups of users. This plugin is often used with the [MBMessages](https://github.com/Mumble-SRL/MBMessages-Android) plugin to being able to send push and messages only to targeted users.


# Installation

#### Installation with gradle

This plugin only works with the latest Kotlin version of MBurger Client SDK so make sure to ad Kotlin Android Studio plugin and Kotlin dependencies to your Android project.

Add this repository to your project level `build.gradle` file under `allprojects`:

```
maven { url "https://dl.bintray.com/mumbleideas/MBurger-Android/" }
```

Then add **MBurger Kotlin** dependency to your `app build.gradle` file:

```
implementation 'mumble.mburger:android_kt:0.5.5'
```

Lastly add `MBAudience` library:

```
implementation 'mumble.mburger:mbaudience-android:0.3.0'
```


# Initialization

To initialize MBMessages you need to add `MBMessages` to the array of plugins of `MBurger`.

```
val plugins = ArrayList<MBPlugin>()
val plugin = MBAudience()
plugins.add(plugin)

MBurger.initialize(applicationContext, "MBURGER_KEY", false, plugins)
```

Then you need to say MBurger to initialize the plugins with the in initPlugins method from MBurger class. If you wish you can add a listener to know when the plugin have been initialized.

```
val listener: MBAudiencePluginInitialized
plugin.initListener = listener

override fun onMBAudienceInitialized() {
   //Plugin has been initialized correctly, can be started
}
```

Once you've done this ask MBurger to start plugins in your main activity (be aware that it has to be an `AppCompatActivity`), then, in app messages will be fetched automatically and showed, if they need to be showed.

```
MBurger.startPlugins(activity)
```


# Tracked data

Below are described all the data that are tracked by the MBAudience SDK and that you will be able to use from the [MBurger](https://mburger.cloud/) dashboard. Most of the data are tracked automatically, for a couples a little setup by the app is neccessary.

* **app\_version**: The current version of the app (version code).
* **locale**: The locale of the phone, the value returned by `Locale.getDefault().language`.
* **sessions**: An incremental number indicating the number of time the user opens the app, this number is incremented at each startup.
* **sessions\_time**: The total time the user has been on the app, tracked by a custom implementation of the `LifecycleObserver`. This time is paused when the app goes in background (using `onMoveToBackground`) .and it's resumed when the app return active (using `onMoveToForeground`).
* **last\_session**: The start date of the last session.
* **push\_enabled**: If push notifications are enabled or not; must be set manually with: `MBAudience.setPushEnabled(context: Context, push_enabled: Boolean)`, the default value is `true`
* **location\_enabled**: If user has given permissions to use location data or not; this is true if `ACCESS_FINE_LOCATION` or `ACCESS_COARSE_LOCATION` is enabled while app in foreground.
* **mobile\_user\_id**: The user id of the user curently logged in MBurger.
* **custom\_id**: A custom id that can be used to filter further.
* **tags**: An array of tags.
* **latitude, longitude**: The latitude and longitude of the last place visited by this device.


# Tags

You can set tags to assign to a user/device (e.g. if user has done an action set a tag), so you can target those users later:

To set a tag or a group of tags:

```
MBAudience.addTag(context:Context, key: String, value: String)
MBAudience.addTags(context:Context, tags: ArrayList<MBTag>)
```

To remove it or clear all:

```
MBAudience.removeTag(context:Context, key: String)
MBAudience.clearTags(context:Context)
```


# Custom Id

You can set a custom id in order to track/target users with id coming from different platforms.

To set a custom id:

```
MBAudience.setCustomID(context: Context, custom_id: String)
```

To remove it:

```
MBAudience.removeCustomID(context: Context)
```

To retrieve the current saved id:

```
MBAudience.getCustomID()
```


# Mobile User Id

This is the id of the user currently logged in MBurger using MBAuth. At the moment the mobile user id is **not sent automatically** when a user log in/log out with MBAuth. It will be implemented in the future but at the moment you have to set and remove it manually when the user completes the login flow and when he logs out.

To set the mobile user id:

```
MBAudience.setMobileUserId(context: Context, mobile_user_id: String)
```

To remove it, if the user logs out:

```
MBAudience.removeMobileUserId(context: Context)
```

To get the currently saved mobile user id:

```
MBAudience.getMobileUserId()
```

###


# Location Data

MBAudience let you track and target user based on their location, the framework uses a foreground `FusedLocationProviderClient` with priority `PRIORITY_BALANCED_POWER_ACCURACY` which **is killed** the moment the app goes in background:

```
MBAudience.startLocationUpdates(context: Context)
```

To stop monitoring location changes you have to call:

```
MBAudience.stopLocationUpdates()
```

If you wish to track user position while app is in background you need to **implement your own location service**, then when you have a new location you can use this API to send it to the framework:

```
MBAudience.setPosition(context: Context, latitude: Double, longitude: Double)
```


# Automation

`MBAutomationAndroid` is a plugin libary for [MBurger](https://mburger.cloud/), that lets you send automatic push notifications and in-app messages crated from the MBurger platform. It has as dependencies [MBMessagesAndroid](https://github.com/Mumble-SRL/MBMessages-Android) and [MBAudienceAndroid](https://github.com/Mumble-SRL/MBAudience-Android). With this library you can also track user events and views.

Using `MBAutomationAndroid` you can setup triggers for in-app messages and push notifications, in the MBurger dashboard and the SDK will show the coontent automatically when triggers are satisfied.

It depends on `MBAutomationAndroid` because messages can be triggered by location changes or tag changes, coming from this SDK.

It depends on `MBAutomationAndroid` because it contains all the views for the in-app messages and the checks if a message has been already displayed or not.

The data flow from all the SDKs is manage entirely by MBurger, you don't have to worry about it.

##


# Installation

#### Installation with gradle

This plugin only works with the latest Kotlin version of MBurger Client SDK so make sure to ad Kotlin Android Studio plugin and Kotlin dependencies to your Android project.

Add this repository to your project level `build.gradle` file under `allprojects`:

```
maven { url "https://dl.bintray.com/mumbleideas/MBurger-Android/" }
```

Then add **MBurger Kotlin** dependency to your `app build.gradle` file:

```
implementation 'mumble.mburger:mbautomation-android:0.3.0'
```

Lastly add `MBAudience` and `MBMessages` library:

```
implementation 'mumble.mburger:mbmessages-android:0.4.15'
implementation 'mumble.mburger:mbaudience-android:0.3.0'
```


# Initialization

To initialize automation you need to insert `MBAutomation` as a `MBurger` plugins, tipically automation is used in conjunction with the `MBMessages` and `MBAudience` plugins.

```
val plugins = ArrayList<MBPlugin>()
val pluginAutomation = MBAutomation()
val pluginAudience = MBAudience()
val pluginMessages = MBMessages()
plugins.add(pluginAutomation)
plugins.add(pluginAudience)
plugins.add(pluginMessages)

MBurger.initialize(applicationContext, "MBURGER_KEY", false, plugins)
```

Once you've done this ask MBurger to start plugins in your main activity (be aware that it has to be an `AppCompatActivity`).

```
MBurger.startPlugins(activity)
```


# Triggers

Every in-appmessage or push notification coming from MBurger can have an array of triggers, those are managed entirely by the MBAutomation SDK that evaluates them and show the mssage only when the conditioon defined by the triggers are matched.

If thre are more than one trigger, they can be evaluated with 2 methods:

* `any`: once one of triggers becomes true the message is displayed to the user
* `all`: all triggers needs to be true in order to show the message.

Here's the list of triggers managed by automation SDK:

**App opening**

`MBTriggerAppOpening`: Becoomes true when the app has been opened n times (`times` property), it's checked at the app startup.

**Event**

`MBTriggerEvent`: Becomes true when an event happens n times (`times` property)

**Inactive user**

`MBTriggerInactiveUser`: Becomes true if a user has not opened the app for n days (`days` parameter)

**Location**

`MBTriggerLocation`: If a user enters a location, specified by `latitude`, `longitude` and `radius`. This trigger can be activated with a ttime delay defined as the `after` property. The location data comes from the [MBAudienceAndroid](https://github.com/Mumble-SRL/MBAudience-Android) SDK.

**Tag change**

`MBTriggerTagChange`: If a tag of the [MBAudienceAndroid](https://github.com/Mumble-SRL/MBAudience-Android) SDK changes and become equals or not to a value. It has a `tag` property (the tag that needs to be checked) and a `value` property (the value that needs to be equal or different in order to activate the trigger)

**View**

`MBTriggerView`: it's activated when a user enters a view n times (`times` property). If the `seconds_on_view` the user needs to stay the seconds defined in order to activate the trigger.


# Add events

You can send events with the `MBAutomation` like this:

```
MBAutomation.addEvent(context, "event")
```

You can specify 2 more parameters, both optional: `name` a name that will be displayed in the MBurger dashboard and a dictionary of additional `metadata` to specifymore fields of the event

```
MBAutomation.sendEvent(context, "event",
                      	name : String? = "name",
                      	metadata: String? = "metadata")
```

Events are saved in a local database and sent to the server every 10 seconds, you can change the frequency setting the `eventsTimerTime` property.


# View Tracking

In MBAutomation the tracking of the views is automatic by using [Application.ActivityLifecycleCallbacks](https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks) to track view automatically on `onActivityCreated`, `onActivityStarted`, `onActivityStopped` and `onActivityDestroyed`. You can disable it changing the static value `trackViewsAutomatically` to false.

The default name for all the Activities is the class name (e.g. if your Activity is called Act\_home you will see Act\_home as the view). If you want to change the name for an Activity you can change its internal name by setting a title on the Manifest or calling `setTitle` on the onCreate.

If you have disabled the automatic tracking and you still want to track the views you can use this function, passing a `FragmentActivity` and, optionally, how much time the Activity has been seen:

```
MBAutomation.trackScreenView(this, time: Long = -1L)
```

As the events, views are saved in a local database and sent to the server every 10 seconds and you can change the frequency setting the `eventsTimerTime` property.


# Stop/Pause tracking

To property stop view and events tracking you should call

```kotlin
MBAutomation.stopAutomation(applicationContext)
```

We suggest to call it when your app goes on background then restart it with

```kotlin
MBAutomation.startEventsAndViewsAutomation(applicationContext)
```

when your app returns to foreground.


# Messages

MBMessages is a plugin libary for [MBurger](https://mburger.cloud), that lets you display in app messages and manage push notifications in your app.

Using this library you can display the messages that you set up in the MBurger dashboard in your app. You can also setup and manage push notifications connected to your MBurger project.

MBMessages depends on the following packages:

* [mburger](https://pub.dev/packages/mburger)
* [mpush](https://pub.dev/packages/mpush)
* [device\_info](https://pub.dev/packages/device_info)
* [http](https://pub.dev/packages/http)
* [path](https://pub.dev/packages/path)
* [path\_provider](https://pub.dev/packages/path_provider)
* [shared\_preferences](https://pub.dev/packages/shared_preferences)


# Installation

You can install the MBAudience SDK using pub, add this to your pubspec.yaml file:

```yaml
dependencies:
  mbmessages: ^0.0.1
```

And then install packages from the command line with:

```bash
$ flutter pub get
```


# Initialization

To initialize the SDK you have to add `MBMessages` to the array of plugins of `MBurger`.

```dart
MBManager.shared.apiToken = 'YOUR_API_TOKEN';
MBManager.shared.plugins = [MBMessages()];
```

To show in app message correctly you have to embed your main widget in a `MBMessagesBuilder` like this:

```dart
@override
Widget build(BuildContext context) {
return MaterialApp(
  ...
    home: MBMessagesBuilder(
      child: Scaffold(
        ...
      ),
    ),
  );
}
```

Why? To present in app messages `MBMessages` uses the `showDialog` function that needs a `BuildContext`. Embedding your main `Scaffold` in a `MBMessagesBuilder` let the SDK know always what context to use to show in app messages.

### Initialize MBMessages with parameters

You can set a couples of parameters when initializing the `MBMessages` plugin:

```dart
MBMessages messagesPlugin = MBMessages(
  messagesDelay: 1,
  automaticallyCheckMessagesAtStartup: true,
  debug: false,
  themeForMessage: (message) => MBInAppMessageTheme(),
  onButtonPressed: (button) => _buttonPressed(button),
);
```

* **messagesDelay**: it's the time after which the messages will be displayed once fetched
* **automaticallyCheckMessagesAtStartup**: if the plugin should automatically check messages at startup. By default it's true.
* **debug**: if this is set to `true`, all the message returned by the server will be displayed, if this is set to `false` a message will appear only once for app installation. This is `false` by default
* **themeForMessage**: a function to provide a message theme (colors and fonts) for in app messages.
* **onButtonPressed**: a callback called when a button of an in app message iis pressed.


# Stylize in app messages

If you want to specify fonts and colors of the messages displayed you can use the `themeForMessage` function and provide a theme for the specified message. For each message you can specify the following properties:

* **backgroundColor**: the color of the background
* **titleStyle**: the text style for the title of the message
* **bodyStyle**: the text style for the body of the message
* **closeButtonColor**: the color of the close button
* **closeButtonBackgroundColor**: the background color of the close button
* **button1BackgroundColor**: the background color for the first button
* **button1TextStyle**: the text style for the first button.
* **button2BackgroundColor**: the background color for the second button
* **button2BorderColor**: the border color for the second button
* **button2TextStyle**: the text style for the second button

Example:

```dart
...

    MBManager.shared.plugins = [
      MBMessages(
        themeForMessage: (message) => _themeForMessage(message),
      ),
    ];

...

  MBInAppMessageTheme _themeForMessage(MBInAppMessage message) {
    if (message.style == MBInAppMessageStyle.bannerTop) {
      return MBInAppMessageTheme(
        titleStyle: TextStyle(
          fontWeight: FontWeight.bold,
          color: Colors.blue,
        ),
      );
    } else {
      return MBInAppMessageTheme(
        titleStyle: TextStyle(
          fontWeight: FontWeight.normal,
          color: Colors.red,
        ),
      );
    }
  }
```


# Push notifications

With this plugin you can also manage the push notification section of MBurger, this is a wrapper around MPush, the underlying platform, so you should refer to the [MPush documentation ](https://github.com/Mumble-SRL/MPush-Flutter) to understand the concepts and to start the push integration. In order to use `MBMessages` instead of `MPush` you have to do the following changes:

Set the push token like this:

```dart
MBPush.pushToken = "YOUR_PUSH_TOKEN";
```

Configure the callbacks and Android native interface like this:

```dart
MBPush.configure(
  onNotificationArrival: (notification) {
    print("Notification arrived: $notification");
  },
  onNotificationTap: (notification) {
    print("Notification tapped: $notification");
  },
  androidNotificationsSettings: MPAndroidNotificationsSettings(
    channelId: 'messages_example',
    channelName: 'mbmessages',
    channelDescription: 'mbmessages',
    icon: '@mipmap/icon_notif',
  ),
);
```

To configure the Android part you need to pass a `MPAndroidNotificationsSettings` to the configure sections, it has 2 parameters:

* `channelId`: the id of the channel
* `channelName`: the name for the channel
* `channelDescription`: the description for the channel
* `icon`: the default icon for the notification, in the example application the icon is in the res folder as a mipmap, so it's adressed as `@mipmap/icon_notif`, iff the icon is a drawable use `@drawable/icon_notif`.

### Request a token

To request a notification token you need to do the following things:

1. Set a callback that will be called once the token is received correctly from APNS/FCM&#x20;

```dart
MBPush.onToken = (token) {
    print("Token retrieved: $token");
}
```

1. Request the token using MPush:

```dart
MBPush.requestToken();
```

### Register to topics

Once you have a notification token you can register this device to push notifications and register to topics:

```dart
MBPush.onToken = (token) async {
  print("Token received $token");
  await MBPush.registerDevice(token).catchError(
    (error) => print(error),
  );
  await MBPush.registerToTopic(MPTopic(code: 'Topic')).catchError(
    (error) => print(error),
  );
  print('Registered');
};
```

The topic are instances of the `MPTopic` class which has 3 properties:

* `code`: the id of the topic
* *\[Optional]* `title`: the readable title of the topic that will be displayed in the dashboard, if this is not set it will be equal to `code`.
* *\[Optional]* `single`: if this topic represents a single device or a group of devices, by default `false`.

### MBurger topics

MBurger has 2 default topics that you should use in order to guarantee the correct functionality of the engagement platform:

* `MBMessages.projectPushTopic()`: this topic represents all devices registred to push notifications for this project
* `MBMessages.devicePushTopic()`: this topic represents the current device

```dart
await MBPush.registerToTopics(
  [
    await MBMessages.projectPushTopic(),
    await MBMessages.devicePushTopic(),
    MPTopic(code: 'Topic'),
  ],
);
```

### Launch notification

If the application was launched from a notification you can retrieve the data of the notification like this, this will be `null` if the application was launched normally:

```dart
Map<String, dynamic> launchNotification = await MBPush.launchNotification();
print(launchNotification);
```


# Rich Notifications

From MBurger you can send medias (images/videos/audio) with a push notification. The link of the media will be sent in the payload of the notifications in the `media_url` field. To view the media sent in the notifications follow tihs steps, as described in the [MPush documentation](https://docs.mpush.cloud/flutter-sdk/ios-setup/rich-notifications). &#x20;

### 1. Create a Notification Service target

In Xcode go to File -> New Target and choose [Notification Service Extension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension)

. This will create a class that will intercept all push notification sent to the app, you will be able to change its content from this class.

![](/files/-MIT6usGhij0mGZOzgVg)

### 2. Download the media

In the notification service class use this code to download the media and attach to the push notification.

```swift
class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            if let mediaUrl = request.content.userInfo["media_url"] as? String, let fileUrl = URL(string: mediaUrl) {
                let type = request.content.userInfo["media_type"] as? String
                downloadMedia(fileUrl: fileUrl, type: type, request: request, bestAttemptContent: bestAttemptContent) {
                    contentHandler(bestAttemptContent)
                }
            } else {
                contentHandler(bestAttemptContent)
            }
        }
    }
    
    func downloadMedia(fileUrl: URL, type: String?, request: UNNotificationRequest, bestAttemptContent: UNMutableNotificationContent, completion: @escaping () -> Void) {
        let task = URLSession.shared.downloadTask(with: fileUrl) { (location, _, _) in
            if let location = location {
                let tmpDirectory = NSTemporaryDirectory()
                let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
                let tmpUrl = URL(string: tmpFile)!
                do {
                    try FileManager.default.moveItem(at: location, to: tmpUrl)
                    
                    var options: [String: String]? = nil
                    if let type = type {
                        options = [String: String]()
                        options?[UNNotificationAttachmentOptionsTypeHintKey] = type
                    }
                    if let attachment = try? UNNotificationAttachment(identifier: "media." + fileUrl.pathExtension, url: tmpUrl, options: options) {
                        bestAttemptContent.attachments = [attachment]
                    }
                    completion()
                } catch {
                    completion()
                }
            }
        }
        task.resume()
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}
```


# Message Metrics

Using `MBMessages` gives you also the chanche to collect informations about your user and the push, those will be displyed on the [MBurger](https://mburger.cloud) dashboard. As described in the prervious paragraph, in order for this to function, you have to tell `MBMessages` that a push has arrived, if you're not seeing correct data make sure to have correctly followed the setup steps for described in the [MPush documentation ](https://github.com/Mumble-SRL/MPush-Flutter).


# Audience

MBAudience is a plugin libary for [MBurger](https://mburger.cloud), that lets you track user data and behavior inside your and to target messages only to specific users or groups of users. This plugin is often used with the [MBMessages](https://github.com/Mumble-SRL/MBMessages-Flutter) plugin to being able to send push and messages only to targeted users.

MBAudience depends on the following packages:

* [mburger](https://pub.dev/packages/mburger)
* [http](https://pub.dev/packages/http)
* [package\_info](https://pub.dev/packages/package_info)
* [permission\_handler](https://pub.dev/packages/permission_handler)
* [shared\_preferences](https://pub.dev/packages/shared_preferences)


# Installation

You can install the MBAudience SDK using pub, add this to your pubspec.yaml file:

```yaml
dependencies:
  mbaudience: ^0.0.1
```

And then install packages from the command line with:

```bash
$ flutter pub get
```


# Initialization

To initialize the SDK you have to add `MBAudience` to the array of plugins of `MBurger`.

```dart
MBManager.shared.apiToken = 'YOUR_API_TOKEN';
MBManager.shared.plugins = [MBAudience()];
```


# Tracked data

Below are described all the data that are tracked by the MBAudience SDK and that you will be able to use from the [MBurger](https://mburger.cloud) dashboard. Most of the data are tracked automatically, for a couples a little setup by the app is neccessary.

* **app\_version**: The current version of the app, retrieved from the [package\_info](https://pub.dev/packages/package_info) package (`packageInfo.version`).
* **locale**: The locale of the phone, the value returned by `Platform.localeName`.
* **sessions**: An incremental number indicating the number of time the user opens the app, this number is incremented at each startup.
* **sessions\_time**: The total time the user has been on the app, this time is paused when the app goes in background (using `WidgetsBindingObserver` app lifecycle state) and it's resumed when the app re-become active.
* **last\_session**: The start date of the last session.
* **push\_enabled**: If push notifications are enabled or not; to determine this value the SDK uses the [permission\_handler](https://pub.dev/packages/permission_handler) package: `Permission.notification.status`.
* **location\_enabled**: If user has given permissions to use location data or not; to determine this value the SDK uses the [permission\_handler](https://pub.dev/packages/permission_handler) package: `Permission.location.status`.
* **mobile\_user\_id**: The user id of the user curently logged in MBurger
* **custom\_id**: A custom id that can be used to filter further.
* **tags**: An array of tags
* **latitude, longitude**: The latitude and longitude of the last place visited by this device


# Tags

You can set tags to assign to a user/device (e.g. if user has done an action set a tag), so you can target those users later:

To set a tag:

```dart
MBAudience.setTag(tag: 'TAG', value: 'VALUE');
```

To remove it:

```dart
MBAudience.removeTag('TAG');
```


# Custom Id

You can set a custom id in order to track/target users with id coming from different platforms.

To set a custom id:

```dart
MBAudience.setCustomId('CUSTOM_ID');
```

To remove it:

```dart
MBAudience.removeCustomId();
```

To retrieve the current saved id:

```dart
String customId = await MBAudience.getCustomId();
```


# Mobile User Id

This is the id of the user currently logged in MBurger using MBAuth. At the moment the mobile user id is not sent automatically when a user log in/log out with MBAuth. It will be implemented in the future but at the moment you have to set and remove it manually when the user completes the login flow and when he logs out.

To set the mobile user id:

```dart
MBAudience.setMobileUserId(1);
```

To remove it, if the user logs out:

```dart
MBAudience.removeMobileUserId();
```

To get the currently saved mobile user id:

```dart
int mobileUserId = await MBAudience.getMobileUserId();
```


# Location Data

MBAudience let you track and target user based on their location. Location is sent to MBurger only if it's distant at least 100m from the last location seen by the SDK.

To start monitoring for location changes call, it will continue monitoring until the stop method is called:

```dart
MBAudience.startLocationUpdates();
```

To stop monitoring location changes you have to call:

```dart
MBAudience.stopLocationUpdates();
```

If you want to implement your location logic yoou can always tell `MBAudience` location data with:

```dart
MBAudience.setCurrentLocation(latitude, longitude);
```

**iOS**

The framework uses the method [startMonitoringSignificantLocationChanges](https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati) of the CoreLocation manager with an accuracy of `kCLLocationAccuracyHundredMeters`. To start monitoring for location changes call, it will continue monitoring until the stop method is called:

**Android**

MBAudience let you track and target user based on their location, the framework uses a foreground `FusedLocationProviderClient` with priority `PRIORITY_BALANCED_POWER_ACCURACY` which is killed the moment the app goes in background. If you wish to track user position while app is in background you need to implement your own location service, then when you have a new location you can use this API to send it to the framework: `setCurrentLocation(latitude, longitude)`


# Automation

`MBAutomation` is a plugin libary for [MBurger](https://mburger.cloud), that lets you send automatic push notifications and in-app messages crated from the MBurger platform. It has as dependencies [MBMessages](https://github.com/Mumble-SRL/MBMessages-Flutter) and [MBAudience](https://github.com/Mumble-SRL/MBAudience-Flutter). With this library you can also track user events and views.

Using `MBAutomation` you can setup triggers for in-app messages and push notifications, in the MBurger dashboard and the SDK will show the coontent automatically when triggers are satisfied.

It depends on `MBAudience` because messages can be triggered by location changes or tag changes, coming from this SDK.

It depends on `MBMessages` because it contains all the views for the in-app messages and the checks if a message has been already displayed or not.

The data flow from all the SDKs is manage entirely by MBurger, yuo don't have to worry about it.

MBAutomation depends on the following packages:

* [mburger](https://pub.dev/packages/mburger)
* [mbmessages](https://pub.dev/packages/mbmessages)
* [mbaudience](https://pub.dev/packages/mbaudience)
* [http](https://pub.dev/packages/http)
* [path](https://pub.dev/packages/path)
* [path\_provider](https://pub.dev/packages/path_provider)
* [shared\_preferences](https://pub.dev/packages/shared_preferences)
* [sqflite](https://pub.dev/packages/sqflite)


# Installation

You can install the MBAudience SDK using pub, add this to your pubspec.yaml file:

```yaml
dependencies:
  mbautomation: ^0.0.1
```

And then install packages from the command line with:

```bash
$ flutter pub get
```


# Initialization

To initialize automation you need to insert `MBAutomation` as an `MBurger` plugin, tipically automation is used in conjunction with the `MBMessages` and `MBAudience` plugins.

```dart
MBManager.shared.plugins = [
  MBAutomation(),
  ... other plugins
];
```

MBAutomation can bbe initialized with 3 optional parameters:

* `trackingEnabled`: If the tracking is enabled or not, setting this to false all the tracking will be disabled
* `eventsTimerTime`: The frequency used to send events and views to MBurger


# Triggers

Every in-app message or push notification coming from MBurger can have an array of triggers, those are managed entirely by the MBAutomation SDK that evaluates them and show the mssage only when the conditioon defined by the triggers are matched.

If thre are more than one trigger, they can be evaluated with 2 methods:

* `any`: once one of triggers becomes true the message is displayed to the user
* `all`: all triggers needs to be true in order to show the message.

Here's the list of triggers managed by automation SDK:

**App opening**

`MBAppOpeningTrigger`: Becoomes true when the app has been opened n times (`times` property), it's checked at the app startup.

**Event**

`MBEventTrigger`: Becomes true when an event happens n times (`times` property)

**Inactive user**

`MBInactiveUserTrigger`: Becomes true if a user has not opened the app for n days (`days` parameter)

**Location**

`MBLocationTrigger`: If a user enters a location, specified by `latitude`, `longitude` and `radius`. This trigger can be activated with a day delay defined as the `afterDays` property. The location data comes from the [MBAudience](https://github.com/Mumble-SRL/MBAudience-Flutter) SDK.

**Tag change**

`MBTagChangeTrigger`: If a tag of the [MBAudience](https://github.com/Mumble-SRL/MBAudience-Flutter) SDK changes and become equals or not to a value. It has a `tag` property (the tag that needs to be checked) and a `value` property (the value that needs to be equal or different in order to activate the trigger)

**View**

`MBViewTrigger`: it's activated when a user enters a view n times (`times` property). If the `secondsOnView` the user needs to stay the seconds defined in order to activate the trigger.


# Send events

You can send events with `MBAutomation` liike this:

```dart
MBAutomation.sendEvent('EVENT_NAME');
```

You can specify 2 more parameters, both optional: `name` a name that will be displayed in the MBurger dashboard and a map of additional `metadata` to specifymore fields of the event

```dart
MBAutomation.sendEvent(
  'purchase',
  name: "PURCHASE",
  metadata: {"quantity": 1},
);
```

Events are saved in a local database and sent to the server every 10 seconds, you can change the frequency setting the `eventsTimerTime` property.


# View Tracking

To track views automatically add an instance of `MBAutomationNavigatorObserver` to the `navigatorObservers` of your app, like this:

```dart
@override
Widget build(BuildContext context) {
  return MaterialApp(
    navigatorObservers: [MBAutomationNavigatorObserver()],
    home: ...,
  );
}
```

The navigator observer will send the name of the `PageRoute` (`route.settings.name`) tto MBurger whenever a new route is pushed or popped.

If you don't wnat to use the navigator observer you can use this function, to track a view manually.

```dart
MBAutomation.trackScreenView('VIEW');
```

As the events, views are saved in a local database and sent to the server every 10 seconds and you can change the frequency setting the `eventsTimerTime` property.


