> ## Documentation Index
> Fetch the complete documentation index at: https://docs.castled.io/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Initialization

## Import Castled SDK dependency

```swift swift
import Castled
```

```objc objc
#import <Castled/Castled-Swift.h>
```

## Initialize the SDK

Initialize the SDK by setting the `app id` available in the Castled Settings page in the `didFinishLaunchingWithOptions` method of the `AppDelegate` class and call the initialize method.

```swift swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  ...
  let config = CastledConfigs.initialize(appId: "<app-id>")

  Castled.initialize(withConfig: config, andDelegate: self)
  ...
  return true
}
```

```objc objc
@interface AppDelegate ()<UIApplicationDelegate,UNUserNotificationCenterDelegate,CastledNotificationDelegate>
{

}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    CastledConfigs *config = [CastledConfigs initializeWithAppId:@"<app-id>"];

    [Castled initializeWithConfig:config andDelegate:self];
    ...
    return YES;
}
```

## User Identification

To identify the user associated with this app instance, use the following method. This is typically invoked immediately after user completes the
sign-in flow of your app. `user-id` is the id that you use internally within your organisation to identify a user.

```swift swift
Castled.sharedInstance.setUserId("<user-id>")
```

```objc objc
[[Castled sharedInstance] setUserId:@"<user-id>" userToken:nil]; 
```

> [!NOTE]
>
> It is recommended to pass an optional **user-token** as the second parameter
> to `setUserId` to mitigate any risk of user impersonation. In the absence of a
> **user-token**, no additional verifications will be done to enforce user
> authenticity. If your **user-id** is random id such as a UUID, **user-token**
> is probably not required. More info on **user-token** can be found in the next
> section.

## Secure User Identification

`user-token` is a unique token for each user generated by your app server. This token is usually issued by the app server after the user
completes the login flow within your app.

```swift swift
Castled.sharedInstance.setUserId("user@org.com", userToken: "<user-token>")
```

```objc objc
[[Castled sharedInstance] setUserId:@"user@org.com" userToken:@"<user-token>"];
```

`user-token` is a Base64 encoded **Hash-based Message Authentication Code** (HMAC). Ensure the hash computation happens in your app server so that `api-key`
is not exposed. You can create an `api-key` in the **Setting > API Keys** page within your Castled account. Contact Castled support for help with integration.

Find sample server code snippets to generate **HMAC** for the `user-id`.

```java java
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;

    public static String calculateHMAC(String userId, String apiKey) throws Exception {
        // Get an instance of the HMAC using SHA-256 hashing algorithm
        Mac sha256Hmac = Mac.getInstance("HmacSHA256");

        // Create a SecretKeySpec using the provided key
        SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");

        // Initialize the Mac with the secret key
        sha256Hmac.init(secretKey);

        // Compute the HMAC of the given data
        byte[] rawHmac = sha256Hmac.doFinal(userId.getBytes(StandardCharsets.UTF_8));

        // Convert the HMAC bytes to a Base64 encoded string
        return Base64.getEncoder().encodeToString(rawHmac);
    }
```

```go go
    import (
        "crypto/hmac"
        "crypto/sha256"
        "encoding/base64"
        "fmt"
    )

    func calculateHMAC(message string, apiKey string) string {
        key := []byte(apiKey)
        h := hmac.New(sha256.New, key)
        h.Write([]byte(message))

        // Encoding the HMAC as a Base64 encoded string
        return base64.StdEncoding.EncodeToString(h.Sum(nil))
    }
```

#### FAQ

> [accordion] How do I rotate the Api Key?
>
> At your server side you can keep the `Api Key` as some config that can be
> easily changed with minimal or no code change. So when you want to rotate
> the key, create a new key from Castled dashboard, update the new key at your
> server side. Ideally you shouldn't disable old token immediately as new user
> token is updated only when `setUserId()` is called. You should allow some grace
> period before disabling the old `Api Key` so that all users gets the updated user token.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.