Countly Documentation

Countly Resources

Here you'll find comprehensive guides to help you start working with Countly as quickly as possible.

Phonegap, Icenium & Meteor

Setting up Countly SDK inside your Phonegap, Cordova, Icenium or Meteor application is straightforward. Just follow these steps.

Using SDK

First run the following to create a Countly demo application.

cordova create countly-demo-js com.countly.demo countly-demo-js
cd countly-demo-js

Add Countly core plugin

cordova plugin add https://github.com/Countly/countly-sdk-js.git


# AND (OPTIONAL) PUSH PLUGIN
cordova plugin add https://github.com/phonegap/phonegap-plugin-push.git

Now add platform of your choice

cordova platform add android
cordova platform add ios

It's important that you make sure you build it with Cordova, as Cordova links folders very well.

cordova build android
cordova build ios

Now run the application directly for Android,

cordova run android

Or iOS:

cordova run ios

Alternatively, you can open the source in Xcode, or Eclipse and move on with further development.

Using SDK with Meteor app

Run this command for Meteor:

meteor add countly:countly-sdk-js

ionic 2.0

npm install -g ionic cordova
ionic start countly-demo-ionic blank
cd countly-demo-ionic
ionic cordova plugin add https://github.com/Countly/countly-sdk-js.git
ionic serve

In your index.html, use the following lines:

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="Countly.js"></script>

If you looking to try out example code, you may wanna look at the index.html in the countly-sdk-js repo in master branch.

Copy and paste into your www/index.html

It has all the required examples you need.

Implementation

Below you can find necessary code snippets to initialize the SDK for sending data to Countly servers. Where possible, use your server URL instead of try.count.ly in case you have your own server.

// initialize
// use your server name below if required.
Countly.init("https://try.count.ly","App_Key");

// change device id
Countly.changeDeviceId("123456", true);

// get device id
Countly.getDeviceID(function(deviceId){
  console.log(deviceId);
}, function(getDeviceIDError){
  console.log(getDeviceIDError);
});

// sending data with salt
Countly.enableParameterTamperingProtection("salt");

Countly.setHttpPostForced(true); // default is false

// send user location
Countly.setLocation(latitude, longitude);

//example to start and stop Countly
Countly.start();
Countly.stop();

Custom events

Here is a quick summary on how to use custom events recording methods and what information they will provide. For more information about how custom events and segmentations work, read this guide first.

Note that all data passed to Countly instance via SDK or API should be in UTF-8.

// example for sending basic custom event
var events = {"eventName":"basic_event","eventCount":1};
Countly.sendEvent(events);

// example for event with sum
var events = {"eventName":"event_sum","eventCount":1,"eventSum":"0.99"};
Countly.sendEvent(events);

// example for event with segment
var events = {"eventName":"event_segment","eventCount":1};
events.segments = {"Country" : "Germany", "Age" : "28"};
Countly.sendEvent(events);

// example for event with segment and sum
var events = {"eventName":"event_segment_sum","eventCount":1,"eventSum":"0.99"};
events.segments = {"Country" : "Germany", "Age" : "28"};
Countly.sendEvent(events);

// TIMED EVENTS
// Basic event
Countly.startEvent("timedEvent");
Countly.endEvent("timedEvent");

// Event with sum
Countly.startEvent("timedEvent");
var events = {
  "eventName": "timedEvent",
  "eventSum": "0.99"
};
Countly.endEvent(events);

// Event with segment
Countly.startEvent("timedEvent");
var events = {
  "eventName": "timedEvent"
};
events.segments = {
  "Country": "Germany",
  "Age": "28"
};
Countly.endEvent(events);

// Event with Segment, sum and count
Countly.startEvent("timedEvent");
var events = {
  "eventName": "timedEvent",
  "eventCount": 1,
  "eventSum": "0.99"
};
events.segments = {
  "Country": "Germany",
  "Age": "28"
};
Countly.endEvent(events);

// TIMED EVENTS

Which server/host should I use inside SDK?

If you are using Countly Enterprise Edition trial servers use https://try.count.ly, https://us-try.count.ly or https://asia-try.count.ly. Basically the domain you are accessing your trial dashboard from.

If you use Community Edition and Enterprise Edition, use your own domain name or IP address like https://example.com or https://IP (if SSL is setup).

User Profiles

In order to set a user profile, use code snippet below. After you send a user data, it can be viewed under Dashboard > User Profiles.

Note that this feature is available for Enterprise Edition.

// example for setting user data
var options = {};
options.name = "Nicola Tesla";
options.username = "nicola";
options.email = "info@nicola.tesla";
options.organization = "Trust Electric Ltd";
options.phone = "+90 822 140 2546";
options.picture = "http://www.trust.electric/images/people/nicola.png";
options.picturePath = "";
options.gender = "Male";
options.byear = 1919;
Countly.setUserData(options);

In order to modify a user's data (e.g increment, etc), the following code sample can be used.

// example for extra user features
Countly.userData.setProperty("keyName", "keyValue");
Countly.userData.increment("keyName");
Countly.userData.incrementBy("keyName", 10);
Countly.userData.multiply("keyName", 20);
Countly.userData.saveMax("keyName", 100);
Countly.userData.saveMin("keyName", 50);
Countly.userData.setOnce("keyName", 200);

Crash reporting

With this feature, Countly SDK will generate a crash report if your application crashes due to an exception, and send it to Countly server for further inspection.

If a crash report can not be delivered to server (e.g. no internet connection, unavailable server), then SDK stores the crash report locally in order to try again later.

Please add to your html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.0/stacktrace.min.js"> </script>

// Using countly crash reports
Countly.enableCrashReporting();

You can also send a custom crash log to Countly using code below.


// Send a custom crash log
Countly.addCrashLog("My crash log from JavaScript");

// Send Exception to the server
Countly.logException(["My Customized error message"], true, {"_facebook_version": "0.0.1"});
Countly.logException(stackFramesFromStackTraceJS, booleanNonFatal, segments);


// Usage Example

app.addCrashLog = function(){
  Countly.addCrashLog("User Performed Step A");
  setTimeout(function(){
    Countly.addCrashLog("User Performed Step B");
  },1000);
  setTimeout(function(){
    Countly.addCrashLog("User Performed Step C");
    console.log("Opps found and error");
    Countly.logException("My Customized error message");
  },1000);

}

View tracking

You can manually add your own views in your application, and each view will be visible under Analytics > Views. Below you can see two examples of sending a view using Countly.recordview function.

// record a view on your application
Countly.recordView("My Home Page");
Countly.recordView("Profile Page");

Push notifications

Since PhoneGap push plugin depends on Firebase SDK, you'd also need to set Firebase by adding google-services.json file for Android & GoogleService-Info.plist for iOS.

  1. First, download them from Firebase Console (it's under Settings -> Project settings).
  2. Then add them to your project root folder.
  3. Finally, add corresponding resource-files to config.xml:
<platform name="android">
    <resource-file src="google-services.json" target="app/google-services.json" />
</platform>
<platform name="ios">
    <resource-file src="GoogleService-Info.plist" />
</platform>
  1. Once done, please install the plugin itself:
cordova plugin add phonegap-plugin-push@2.2.0

... and set it up by following instructions here.

Here is code usage example:

// This is regular code for cordova push plugin 
var push = PushNotification.init(android: {sound: true});

// On receiving registrationid from google / apple 
// send it to countly server using the below method
push.on('registration', function(data) {
    Countly.sendPushToken({
        "token": data.registrationId,
        "messagingMode": Countly.messagingMode.DEVELOPMENT,
        // Countly.messagingMode.DEVELOPMENT
        // Countly.messagingMode.PRODUCTION
        // Countly.messagingMode.ADHOC
        
    })

    // data.registrationId
});

// Receive push notification in a regular way using countly.
// When you send a push notification from countly server, 
// Users will recevive notification in the below method listerner.
// The data object is the json information send using the countly server.
push.on('notification', function(data) {
    // data.message,
    // data.title,
    // data.count,
    // data.sound,
    // data.image,
    // data.additionalData
});

Limitations of Cordova

Due to limitations of the way push is handled in a Cordova application, it's not possible to report back actions done when a push notification is received.

Troubleshooting

If you get the following error during implementation (for versions before v1.0 SDK):

NSPersistentStoreCoordinator with a nil model

In this case, go to https://github.com/Countly/countly-sdk-js/tree/master/src/ios/sdk. Drag and drop "Countly.xcdatamodeld" folder into your plugins folder, and then build it using Xcode.

Warning about Java

Note: As per the new release v1.0 you will need Java 1.8 to bundle the application. You will need to update the CLASSPATH environment variable of Java and Javac to Java version 1.8

If you would like to set logging, use code snippet below in your code.

// example for setLoggingEnabled
Countly.setLoggingEnabled();

Optional parameters during initialization
You can provide optional parameters that will be used during begin_session request. They must be set right after the init function so that they are set before the request is sent to the server. To set them, use the setOptionalParametersForInitialization function. If you want to set those optional parameters, this function has to be called every time the app starts. If you don't to set one off those values, leave that field null.

The optional parameters are:

  • Country code: ISO Country code for the user's country
  • City: Name of the user's city
  • Location: Comma separate latitude and longitude values, for example "56.42345,123.45325"

//setting optional parameters
Countly.setOptionalParametersForInitialization({
    city: "Tampa",
    country: "US",
    latitude: "28.006324",
    longitude: "-82.7166183"
});


//and then call the below code
Countly.init(this, "https://YOUR_SERVER", "YOUR_APP_KEY", "YOUR_DEVICE_ID")

Ratings

// Ratings can be from 1 - 5;
Countly.sendRating(5);