# iOS v-0.0.7 / Android v-0.0.2

### Imports&#x20;

To integrate the Truvideo SDK, include the following platform-specific imports:

{% tabs %}
{% tab title="C#" %}

```csharp
#if IOS
using UIKit;
using Foundation;
using TruvideoCameraiOS;
#endif

#if ANDROID
using Application = Android.App.Application;
using TruVideoCoreAndroidBinding;
using TruVideoCoreLib = TruVideoCoreAndroid.DotnetCoreTruvideo;
#endif
```

{% endtab %}
{% endtabs %}

### Async Callback Wrapper

For handling asynchronous callbacks in Android, use the following method:

{% tabs %}
{% tab title="C#" %}

```csharp
#if ANDROID
    private Task<T> ExecuteCallbackAsync<T>(Action<CoreCallback> action)
    {
        var tcs = new TaskCompletionSource<T>();

        action.Invoke(new CoreCallback(
            success => MainThread.BeginInvokeOnMainThread(() =>
                tcs.TrySetResult((T)Convert.ChangeType(success, typeof(T)))),
            failure => MainThread.BeginInvokeOnMainThread(() => tcs.TrySetException(new Exception(failure)))
        ));

        return tcs.Task;
    }
#endif

#if IOS
    private Task<T> ExecuteCallbackAsync<T>(Action<Action<string, NSError>> nativeCall) {
        var tcs = new TaskCompletionSource<T>();
        nativeCall((nsResult, error) => {
            if (error != null)
            {
                tcs.SetException(new Exception(error.LocalizedDescription));
            }
            else {
                // Convert NSString to string
                string result = nsResult.ToString();
                tcs.TrySetResult((T)Convert.ChangeType(result, typeof(T)));
               // tcs.SetResult(result);
            }
        });
        return tcs.Task;
    }
#endif
```

{% endtab %}
{% endtabs %}

This function executes image-related actions asynchronously and ensures results are processed on the main thread.

### Initialize SDK

InitAppInitializer is used to Initialize the SDK&#x20;

{% tabs %}
{% tab title="C#" %}

```csharp
String _init = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.InitAppInitializer(Application.Context, cb));
```

{% endtab %}
{% endtabs %}

### Authentication Status

The Truvideo SDK provides two properties that serve to check the authentication status:&#x20;

* `isAuthenticated()` : Returns true or false indicating whether the client is authenticated. Please note that authentication may be expired.
* `isAuthenticationExpired()` : Return true or false indicating whether the authentication is expired. If the client is not authenticated, it always returns false.

{% tabs %}
{% tab title="C#" %}

```csharp
#if ANDROID
string _isAuthenticate = await ExecuteCallbackAsync<bool>(cb => TruVideoCoreLib.IsAuthenticated(cb));
string _isAuthenticationExpired = await ExecuteCallbackAsync<bool>(cb => TruVideoCoreLib.IsAuthenticationExpired(cb));
#endif

#if IOS
string _isAuthenticate = await ExecuteCallbackAsync<bool>(cb => TruvideoCore.Shared.IsAuthenticatedWithCompletionHandler(cb));
string _isAuthenticationExpired = await ExecuteCallbackAsync<bool>(cb => TruvideoCore.Shared.IsAuthenticationExpiredWithCompletionHandler(cb));
#endif
```

{% endtab %}
{% endtabs %}

### How to authenticate&#x20;

The authenticate method requires the following inputs:

1. ApiKey: A string provided by Truvideo upon registration.
2. Payload: Essential data containing device information, generated internally using the `generatePayload()` function.
3. Signature: Encrypt the payload with the provided secret key using the SHA256 algorithm to regenerate the signature.

Upon completion, it triggers the onReady callback or the onError callback in case of an error.

<pre data-overflow="wrap"><code>Note
<strong>The API key and Secret key are provided by the TRUVideo SDK team.
</strong></code></pre>

### Algorithm for encoding the signature

To encode the payload, utilize the following function for conversion: The string undergoes conversion using the SHA256 algorithm, incorporating the provided secret key.

The syntax for utilizing this encoding process appears as follows:

{% tabs %}
{% tab title="C#" %}

```csharp
string _signature = HashHelper.ToSha256String(_secretKey, payload);
```

{% endtab %}
{% endtabs %}

```csharp
using System.Security.Cryptography;
using System.Text;
namespace TruVideoSampleApp;
public static class HashHelper
{
    public static string? ToSha256String(string signature, string payload)
    {
        try
        {
            var keyBytes = Encoding.UTF8.GetBytes(signature);
            var payloadBytes = Encoding.UTF8.GetBytes(payload);
            using var hmac = new HMACSHA256(keyBytes);
            var hashBytes = hmac.ComputeHash(payloadBytes);
            // Convert to hex string
            var hexString = new StringBuilder();
            foreach (var b in hashBytes) hexString.Append(b.ToString("x2")); // formats byte as lowercase hex
            return hexString.ToString();
        }
        catch (Exception ex)
        {
            // Log or handle exception as needed
            Console.WriteLine(ex);
            return null;
        }
    }
}
```

<pre data-overflow="wrap"><code>Note 
<strong>We suggest avoiding storing the secret within the host application. Instead, set up a private backend owned by you. This backend will handle the payload from the Truvideo SDK and generate the signature. By doing this, you can prevent the secret from being exposed, reducing the risk of security issues
</strong></code></pre>

### Authentication process

The entire Authentication process is demonstrated below :

{% tabs %}
{% tab title="C#" %}

```csharp
#if ANDROID
string _init = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.InitAppInitializer(Application.Context, cb));
// Step 1: Check if authenticated
bool _isAuthenticate = await ExecuteCallbackAsync<bool>(cb => TruVideoCoreLib.IsAuthenticated(cb));
// Step 2: Check if authentication is expired
bool _isAuthenticationExpired = await ExecuteCallbackAsync<bool>(cb => TruVideoCoreLib.IsAuthenticationExpired(cb));

// Step 3: Generate payload
string _payload = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.GeneratePayload(cb));

if (!_isAuthenticate || _isAuthenticationExpired)
{
    // Step 4: Generate SHA-256 signature
    string _signature = HashHelper.ToSha256String(_secretKey, payload);

    // Step 5: Authenticate with API Key, Payload, and Signature
    string authResult = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.Authenticate(_apiKey, _payload, _signature, "", cb));
    MainThread.BeginInvokeOnMainThread(() => AuthenticateButtonLabel.Text = $"Result: {authResult}");
}

// Step 6: Initialize Authentication
string _initAuthResult = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.InitAuthentication(cb));
MainThread.BeginInvokeOnMainThread(() => AuthenticateButtonLabel.Text = $"Result: {_initAuthResult}");
    
#elif IOS
await Task.Run(async () =>
{
    // Step 1: Check if authenticated
    bool _isAuthenticate = await ExecuteCallbackAsync<bool>(cb => TruvideoCore.Shared.IsAuthenticatedWithCompletionHandler(cb));
    //_isAuthenticate = Convert.ToBoolean(isAuthenticate);

    // Step 2: Check if authentication is expired
    bool _isAuthenticationExpired = await ExecuteCallbackAsync<bool>(cb => TruvideoCore.Shared.IsAuthenticationExpiredWithCompletionHandler(cb));

    // Step 3: Generate payload
    string payload = await ExecuteCallbackAsync<string>(cb => TruvideoCore.Shared.GeneratePayload(cb));

    if (!_isAuthenticate || _isAuthenticationExpired)
    {
        // Step 4: Generate SHA-256 signature
        string signature = HashHelper.ToSha256String(_secretKey, payload);

        // Step 5: Authenticate with API Key, Payload, and Signature
        string authResult = await ExecuteCallbackAsync<string>(cb => TruvideoCore.Shared.AuthenticateWithApiKey(apiKey, payload, "", signature, cb));
    }

    // Step 6: Initialize Authentication
    string initAuthResult = await ExecuteCallbackAsync<string>(cb => TruvideoCore.Shared.InitAuthenticationWithCompletionHandler(cb));
    MainThread.BeginInvokeOnMainThread(() =>
    {
        ActivityIndicator.IsRunning = false;
        AuthenticateButtonLabel.Text = " Authentication Success";
        //CheckAuthentication(); // Refresh UI after authentication
    });
});
#endif
```

{% endtab %}
{% endtabs %}

### Clear Authentication

To delete the current session and erase all associated authentication data, utilize the  `clearAuthentication` method

{% tabs %}
{% tab title="C#" %}

```csharp
#if ANDROID
string _clear = await ExecuteCallbackAsync<string>(cb => TruVideoCoreLib.ClearAuthentication(_secretKey, _payload, cb));
#endif

#if IOS
string clear = await ExecuteCallbackAsync<string>(cb => TruvideoCore.Shared.ClearAuthentication(payload, secretKey, cb));
#endif
```

{% endtab %}
{% endtabs %}

This command will remove all authentication data and reset the session.
