Principle

The Cordova plugin can be used for Cordova Applications targeting iOS or/and Android application.

SDK Versions

The Cordova plugin ships both iOS and Android SDK Version. This version uses:

Installation

  1. Download the FollowAnalytic from the FollowAnalytics Platform

  2. Run the following command of cordova (Be sure to have cordova install)

    cordova plugin add /path/to/fa-sdk-phonegap-plugin

Configuration

IOS

  1. In your AppDelegate.m, add this import #import <FollowApps/FAFollowApps.h>

  2. In your AppDelegate.m, add this line in the method didFinishLaunchingWithOptions

    [FAFollowApps configureWithId:API_KEY_STRING debugStateOn:FADEBUG options:launchOptions];

Android

  1. Dependency:

The FollowAppsCordovaPlugin for Android depends to google-play-service version 8.4.0 as framework. So you need to install or update Google Play Services from the Android Extras section using the Android SDK manager (run android).

  1. FollowAnalytics API KEY

Inside your application tag add this meta tag with your API KEY*

    <application>
        .....
      <meta-data android:name="FAID" android:value="API_KEY_STRING" />
        .....
    </application>
  1. Initialization

Create an Application Class and initialize the FollowAnalytics SDK in it

    import android.app.Application;
    import com.followapps.android.* ;

    public class MainApplication extends Application {

        @Override
        public void onCreate() {
            super.onCreate();
            FollowApps.init(this);
            FollowApps.registerGcm()
        }
    }

Don't forget to reference your application class in your AndroidManifest.xml:

    <application ... android:name="MainApplication">

Usage

Event logging

To log event or error you could do as following:

    <a href="#" onclick="FAFollowApps.logEvent('My event', 'My event details')">Log an event</a>
    <a href="#" onclick="FAFollowApps.logError('My error', '')">Log an error</a>
    <a href="#" onclick="FAFollowApps.logEvent('My event', {'hello': 'Hi', 'How are you': 'good!'})">Log an event with hash</a>

Attributes

User Identifier

If users can sign in somewhere in your app, you can specify their identifier to the SDK. This way, you will be able to relate crashes to specific users, link your users between FollowAnalytics and your CRM, and more.

To do so, use:

    FAFollowApps.setUserId(“user_id");

If you want to remove the user identifier (in case of a sign out for instance), please use the method FAFollowApps.unsetUserID();.

User attributes

To set user profile information:

            FAFollowApps.setUserLastName("user_last_name_value");
            FAFollowApps.setUserFirstName("user_first_name_value");
            FAFollowApps.setUserEmail("user_email_value"); 
            FAFollowApps.setUserCity("user_last_city_value"); "// ex:Paris"
            FAFollowApps.setUserBirthDate("2015-10-10");
            FAFollowApps.setUserProfilePicture("user_profile_picture_value");
            FAFollowApps.setUserGender("male");                     // ex: the value must be one of { "male","female", or "other"}
            FAFollowApps.setUserCountry("user_country_value");  // ex: France"
            FAFollowApps.setUserRegion("user_region_value");        // ex: Ile-de-France"

Custom attributes

1. Set a custom attribute

For example, to set the user's job:

 FAFollowApps.setUserAttribute("key_job", "Taxi driver");

2. Delete a custom attribute value

You can delete the value of an attribute by its key. For example, to delete the user's job

FAFollowApps.deleteUserAttribute("key_job");

3. Set of Attributes

You can add or remove an item to or from a set of attributes.

To add an item:

 FAFollowApps.addToUserAttributeSet("key_language","English");
 FAFollowApps.addToUserAttributeSet("key_language","Portuguese");

To remove an item:

 FAFollowApps.removeFromUserAttributeSet("key_language","Portuguese");  //Removes item "Portuguese" from set of languages

To clear a set:

 FAFollowApps.emptyUserAttributeSet("key_language");  //Removes all the items from the set and deletes it.

4. Other types

You can also log other types of attributes like:

    FAFollowApps.setNumber('key', "1.0") // will be logged as an integer
    FAFollowApps.setNumber('key', "1") // will be logged as a double
    FAFollowApps.setString('key', "A custom string attribute")
    FAFollowApps.setBoolean('key', "true")
    FAFollowApps.setBoolean('key', false)

Push Notification

Register for push

In case you want to register for push through a webview, you need to call registerForPush(), e.g.:

<a href="#" onclick="FAFollowApps.registerForPush()">register for push</a>

You can also specify your own gcm senderId as following:

Deeplinking

<a href="#" onclick="FAFollowApps.registerForPush('my-gcm-sender-id')">register for push with my gcm sender id</a>

Deeplinking

iOS

Current notification (iOS)

In order to be able to receive the custom parameters sent within a Push Notification or an In App message payload you'll need to implement the followAppsShouldHandleParameters:actionIdentifier:actionTitle:completionHandler: method. Inside your javascript files you'll have to implement a method that will be called from this Objective-C method. If you implement, or instance, a method called doAmazingThings() as follows:

function doAmazingThings(args) {
    console.log(args);
    var currentdate = new Date();
    var datetime = "Last Sync: " + currentdate.getDate() + "/"
    + (currentdate.getMonth()+1)  + "/"
    + currentdate.getFullYear() + " @ "
    + currentdate.getHours() + ":"
    + currentdate.getMinutes() + ":"
    + currentdate.getSeconds();
    document.getElementById('some_element').innerHTML = (datetime);
    console.log('done');
}

You'll be able to call the doAmazingThings() method using the following Objective-C code:

- (void)followAppsShouldHandleParameters:(NSDictionary *)openingParameters
                        actionIdentifier:(NSString *)actionIdentifier
                             actionTitle:(NSString *)actionTitle
                       completionHandler:(void (^)())completionHandler
{
    if (actionIdentifier)
    {
      // here you'll have the identifier for custom push notification actions
    }
    if (completionHandler != nil) {
      // always call the completionHandler, if any
        completionHandler();
    }
    NSData *data = [NSJSONSerialization dataWithJSONObject:openingParameters
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *functionCall = [NSString stringWithFormat:@"doAmazingThings(%@)", jsonString];
    [YOUR_WEBVIEW_INSTANCE stringByEvaluatingJavaScriptFromString:functionCall];
}

Last notification (iOS)

Some applications might not be able to receive the notification custom parameters. Although unlikely, you can call lastPushCampaignParams to get the latest JSON containing the custom parameters passed by the Notification.

Note this is a one shot call as a second call to this method will return an empty JSON.

For iOS,if a push notification is received while the application is on the background it may not be ready to execute the function called from iOS native code. When this happens use the FALastPushMessageContent method to recover the last custom parameters passed by the notification. This function should be used in response to the deviceready event from PhoneGap/Cordova.
To do this you'll need to modify the function inside plugin javascript file. Check the method implementation inside the FAFollowApps.js file in order to see some implementation options.

Android

Default behavior

By default, when the user clicks on a Push notification shown by the FollowAnalytics SDK, an Intent starting a new instance of your main activity is launched. You can retreive any custom parameter in the Java code by adding the following lines in your onCreate method.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String value1 = extras.getString("a_custom_param_key");
            String value2 = extras.getString("another_key");
            // or retrieve all the pairs
            for (String key : extras.keySet()) {
                Object value = extras.get(key);
                  // …
              }

            // Do what you want with the custom values
          }
    }

Handle deeplinking from Java

If you want more control, you can implement in your Java code the MessageHandler interface, and declare it in your application class, like in the following example.

    public class MyAwesomePushMessageHandler implements MessageHandler {

        @Override
        public void onPushMessageClicked(Context context, Map<String, String> data) {
            String value1 = data.get("a_custom_param_key");
            String value2 = data.get("another_key");

            // Silently do stuff ...
            // .. or start an activity

            Intent intent = new Intent(context, SpecificActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

        @Override
        public void onInAppMessageClicked(Context context, String buttonText, Map<String, String> data) {
            // Same as the above method, but from a in-app message !
        }
    }

If you define a custom MessageHandler, you must declare it in your Application, after the FollowApps.init(this) line:

    FollowApps.setMessageHandler(new MyAwesomePushMessageHandler());

Handle deeplinking from javascript

In your device ready, let we know when the device is ready:

    onDeviceReady: function() {
            ...
            window.FAFollowApps = cordova.require("com/cordova/followapps/plugin");
            FAFollowApps.handleDeeplink();
            FAFollowApps.on("onPushMessageClicked",function(data){
                      console.log(JSON.stringify(data));

            });
             FAFollowApps.on("onPushDeeplinkingClicked",function(data){
                      console.log(JSON.stringify(data));

                            });
             FAFollowApps.on("onInAppMessageClicked",function(data){
                      console.log(JSON.stringify(data));

               });

              ....
    },

Open external WebView

The plugin allows you to launch a native web view with a given url and be able to performs logs from that external resource. In order to do so, if you want to open url https://s3-eu-west-1.amazonaws.com/fa-sdk-files/index.html in a native web view launched from your html code, call the following method from your PhoneGap HTML:

FAFollowApps.openWebView(URL, TITLE, CLOSE_BUTTON_TEXT);

Somethign like:

<a href="#" onclick="FAFollowApps.openWebView('https://s3-eu-west-1.amazonaws.com/fa-sdk-files/index.html', 'Test Log', 'Close'); return false;">Open WebView with title</a>

The URLargument will contain the url of the page to display – required – , the TITLE argument will be shown as the title for the NavigationBar – optional, iOS only - , and the CLOSE_BUTTON_TEXT will contain the text for the close button – optional, iOS only, defaults to “close”.

Please check the html at https://s3-eu-west-1.amazonaws.com/fa-sdk-files/index.html to see how to tag your external pages.

Current available methods are: - logEvent(name, details) - logError(name, details) - setUserId(userId) - unsetUserId()

NOTE: if you're tagging from a link and the link has a real href set, the sdk will handle that for you, performing the onclick action and redirecting you right after.

Plugin events:

The plugin provides the following events : onPushMessageClicked , onPushDeeplinkingClicked and onInAppMessageClicked.

PushMessageClicked event:

When the user click on the push, you can retrieve all the added parameter as following:

``` FAFollowApps.on("onPushMessageClicked",function(data){ //The argument data is an object Json.You can retrieve your value by data.my_key key/value json

 });

```

onPushDeeplinkingClicked event

When the user click on the push, you can retrieve the url as following:

     FAFollowApps.on("onPushDeeplinkingClicked",function(data){
                 //var my_url = data.url;
                // And do something with it

     });

onInAppMessageClicked event

When the user click on the the in-app button, you can retrieve all the added parameter as following:

     FAFollowApps.on("onInAppMessageClicked",function(data){
                 //The argument data is an object Json.You can retrieve your value by data.my_key key/value json;
                 //the label of button clicked is data.button;

     });

The argument data is the javascript key-value object, you can retrieve the value by the key as following : data["deepurl"]

Rich Campaign pause/resume

You can stop the display of Rich Campaigns in screens where you don't want them to appear. In order to do this call the pauseRichCampaignDisplay.
In order to resume the display of Rich Campaigns use the resumeRichCampaignDisplay method.

URL Scheme to allow full debugging

The FollowAnalytics platform enables you to test campaigns before publishing them. To do so, you need the ID of the device you'll use for the test.

Programmatically, you can just call:

FollowApps.getDeviceId()

If you use a version lower than 4.0.0, to let your application users to retrieve their device ID, edit your AndroidManifest.xml file to add this:

<activity android:name="com.followapps.android.internal.activities.DeviceIdActivity" >
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="followanalytics.com"
            android:path="/deviceId"
            android:scheme="%YOUR_APP_PACKAGE_NAME%" />
    </intent-filter>
</activity>

Once installed, your users can open in a browser (not Chrome ) this URI:

%YOUR_APP_PACKAGE_NAME%://followanalytics.com/deviceId

It will open an activity containing the deviceId.

Note that it does not work with Chrome, because it searches on Google instead of opening the URL. If you have no other browser installed, you can install Firefox.

Migration to 4.1.0

Since the version 4.1.0, the plugin Followanalytics is updated to respect cordova plugin standard. So to call a method, you have to init FAFollowApps instance and call the method.

You can always continue to use the deprecated method.

*All method are renamed and the manner theses methods are called is changed

For example :

FALogEvent('My event', 'My event details')

became

FAFollowApps.logEvent('My event', 'My event details')

Troubleshooting

If you eventually run into an error like:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

Be sure to replace the line

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

on your index.html by

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'" >

This will enable the logging of events.