Implementing Feature

Now, you are ready to begin implementation of Cloud Services feature. Our cross-platform Cloud Services component acts as a bridge between your application and native platform.

Cloud Services supports the following data types for storing and retrieving from cloud.

  • Bool
  • Long
  • Double
  • String
  • List
  • Dictionary

Collections can be nested but make sure the nested types are listed above.

Use NPBinding.CloudServices to access Cloud Services features from your code.

Note: All the classes, datatypes related to the plugin are placed under namespace VoxelBusters.NativePlugins. Add this namespace in your script before accessing any of the features.


Initialise Service

First thing, we need to do is to call Initialise method to initialise the cloud services component.

And to do that, we call Initialise.

NPBinding.CloudServices.Initialise();

This initialise call will try to connect with cloud and see if any changes are available. Based on the initilisation status, It will trigger CloudServices.KeyValueStoreDidInitialiseEvent event with a status value. So, make sure you register to this event ahead.

You need to register to CloudServices.KeyValueStoreDidChangeExternallyEvent event as well to get external changes if any.

  // Register for the event
  void OnEnable()
  {
       CloudServices.KeyValueStoreDidInitialiseEvent     += OnKeyValueStoreInitialised;
  }

  void OnDisable()
  {
       CloudServices.KeyValueStoreDidInitialiseEvent     -= OnKeyValueStoreInitialised;
  }

Read data from Cloud Service

As listed above, Cloud services provides options to save different data types and read them back. Each data item saved needs to be stored with a unique key and can be read with the same key.

The data retrieved from the read methods is same as the data available on cloud (assuming sync happens by the time of reading the value).

// Get Bool
bool boolValueOnCloud = NPBinding.CloudServices.GetBool(KEY_FOR_BOOL);

// Get Long
long longValueOnCloud = NPBinding.CloudServices.GetLong(KEY_FOR_LONG);

// Get Double
double doubleValueOnCloud = NPBinding.CloudServices.GetDouble(KEY_FOR_DOUBLE);

// Set String
string stringValueOnCloud = NPBinding.CloudServices.GetString(KEY_FOR_STRING);

// Set List
IList listValueOnCloud = NPBinding.CloudServices.GetList(KEY_FOR_LIST);

// Set Dictionary
IDictionary dictionaryValueOnCloud = NPBinding.CloudServices.GetDictionary(KEY_FOR_DICTIONARY);

Save Data to Cloud

You can set the data directly with the below allowed methods and incase of a conflict it throws CloudServices.KeyValueStoreDidChangeExternallyEvent event. It's responsiblity of the developer to resolve the conflict in the callback. For finding more information on conflict resolution, check Conflict Resolution section below.

// Set Bool
NPBinding.CloudServices.SetBool(KEY_FOR_BOOL, false);

// Set Long
NPBinding.CloudServices.SetLong(KEY_FOR_LONG, 24333333L);

// Set Double
NPBinding.CloudServices.SetDouble(KEY_FOR_DOUBLE, 2.300);

// Set String
NPBinding.CloudServices.SetString(KEY_FOR_STRING, "sample string");

// Set List
List<string> list = new List<string>();
list.Add("string1");

NPBinding.CloudServices.SetList(KEY_FOR_LIST, list);

// Set Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["key1"] = "value1";

NPBinding.CloudServices.SetDictionary(KEY_FOR_DICTIONARY, dict);

Remove a Key from Cloud

If you want to remove a key linked to some data which is no more required, delete it from the cloud.

 NPBinding.CloudServices.RemoveKey(KEY_TO_REMOVE);

Synchronise local and cloud copy Manually

There will be some cases where you want to be sure that your local data is synced with the cloud. Only in those cases call Syncronise method.

Its NOT recommended to call this method (mainly on iOS) often. By default, Syncronise happens at regular intervals automatically under the hood.

NPBinding.CloudServices.Synchronise();

Once syncronise is successful, KeyValueStoreDidSynchroniseEvent event is triggered. So, register it a head to listen it.

void OnEnable()
{
     CloudServices.KeyValueStoreDidSynchroniseEvent     += OnKeyValueStoreDidSynchronise;
}

private void OnKeyValueStoreDidSynchronise (bool _success)
{
    if (_success)
    {
        Debug.Log("Successfully synchronised in-memory keys and values.");
    }
    else
    {
        Debug.Log("Failed to synchronise in-memory keys and values.");
    }
}

void OnDisable()
{
     CloudServices.KeyValueStoreDidSynchroniseEvent     -= OnKeyValueStoreDidSynchronise;
}

Conflict Resolution

Whenever a conflict happens, CloudServices.KeyValueStoreDidChangeExternallyEvent event is triggred.

This event will be called for a limited set of reasons. You can find the reasons in eCloudDataStoreValueChangeReason enum. Check the descriptions below.

  • SERVER : This occurs when another instance of your app using same cloud service account, uploads a new value.
  • INITIAL_SYNC : This occurs when an attempt to write to key-value storage was discarded because an initial download from cloud server has not yet happened.
  • QUOTA_VIOLATION : This occurs when your app’s key-value store has exceeded its space quota on the cloud server.
  • STORE_ACCOUNT : This occurs when user has changed the cloud service account. The keys and values in the local key-value store have been replaced with those from the new account.

CloudServices.KeyValueStoreDidChangeExternallyEvent

This event is called when ever there is data externally changed. This event returns the list of keys that got changed externally.

When this event is triggered, it overwrites the local cloud data with the values of cloud. So, in case of a conflict its up to the developer to compare the local and cloud values and decide which value to use finally.

This event is triggered when ever there is a conflict/change of data externally. Conflict can occur when ever same user’s game insatances are running in more than one device and both change the same cloud value keys.

To resolve the conflicts properly, its advised to maintain a duplicate copy of data set to the cloud. This is because, on conflict, the data in the local will be replaced with cloud data forcefully. So, the copy developer maintains helps in resolving the conflict.


// Register for the event
void OnEnable()
{
     CloudServices.KeyValueStoreDidChangeExternallyEvent     += OnKeyValueStoreChanged;
}

private void OnKeyValueStoreChanged (eCloudDataStoreValueChangeReason _reason, string[] _changedKeys)
{
    Debug.Log("Cloud key-value store has been changed.");
    Debug.Log(string.Format("Reason: {0}.", _reason));

    if (_changedKeys != null)
    {
        Debug.Log(string.Format("Total keys changed: {0}.", _changedKeys.Length));
        Debug.Log(string.Format("Pick a value from old and new and set the value to cloud for resolving conflict."));

        foreach (string _changedKey in _changedKeys)
        {
            if (_changedKey.Equals(KEY_FOR_LONG)) // Shows example of resolving a conflict
            {
                long _newCloudLongValue = NPBinding.CloudServices.GetLong(_changedKey);
                Debug.Log(string.Format("New value for key: {0} is {1}. Old value is {2}", _changedKey, _newCloudLongValue, m_longValue)); 
                // Lets assume, we pick the bigger value and set it here.
                long _biggerValue = _newCloudLongValue > m_longValue ? _newCloudLongValue : m_longValue;

                NPBinding.CloudServices.SetLong(_changedKey, _biggerValue);

                Debug.Log(string.Format("Picking bigger value {0} and setting to cloud.", _biggerValue));           
            }
            else if (_changedKey.Equals(kKeyForDoubleValue))
            {
                Debug.Log(string.Format("New value for key: {0} is {1}", _changedKey, NPBinding.CloudServices.GetDouble(_changedKey))); 
            }

        }
    }
}

void OnDisable()
{
     CloudServices.KeyValueStoreDidChangeExternallyEvent     -= OnKeyValueStoreChanged;
}

In the above code, m_longValue is there in local memory and is used to resolve incase of a conflict. Here max value of both cloud value and local value are considered and set to the cloud again.

This makes sure we will have highest value all the time on cloud. This scenario can be used for storing a High Score value for a player.

Along with list of keys that got changed, It returns a reason for what the event got called. Look for eCloudDataStoreValueChangeReason enum to find different reasons for getting this event triggered.

results matching ""

    No results matching ""