# Selfie Capture

## Initializing the SDK

To get started with the **Unico Check** iOS SDK, import the SDK and implement the **`AcessoBioManagerDelegate`** interface within the ViewController you want to use.

The implementation of this class is straightforward and can be done with just a few lines of code. All you need to do is instantiate the *builder*, providing the *context* and *environment* in question, and override the callback methods with the business logic of your application:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
.m:
#import "ViewController.h"
#import <AcessoBio/AcessoBio.h>

@implementation ViewController: UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];  
    unicoCheck = [[AcessoBioManager alloc]initWithViewController:self];
}

- (void)onErrorAcessoBioManager:(ErrorBio *)error {
  // your code
}

- (void)onSystemChangedTypeCameraTimeoutFaceInference {
  // your code
}

- (void)onSystemClosedCameraTimeoutSession {
  // your code
}

- (void)onUserClosedCameraManually {
  // your code
}
@end
```

{% endtab %}

{% tab title="Swift" %}

```kotlin
import UIKit
import AcessoBio

class ViewController: UIViewController, AcessoBioManagerDelegate {
  var unicoCheck: AcessoBioManager!

  override func viewDidLoad() {
    super.viewDidLoad()      
    unicoCheck = AcessoBioManager(viewController: self)
  }

  func onErrorAcessoBioManager(_ error: ErrorBio!) {
      // your code
  }

  func onUserClosedCameraManually() {
      // your code
  }

  func onSystemClosedCameraTimeoutSession() {
      // your code
  }

  func onSystemChangedTypeCameraTimeoutFaceInference() {
      // your code 
  }
}
```

{% endtab %}
{% endtabs %}

## Environment configuration <a href="#environment-configuration" id="environment-configuration"></a>

Configure the environment that will be used to run the SDK. Use the enumerated environment that contains the following enumerates:

* `PROD`: for production environment;
* `UAT`: for approval environment.

See how to implement it in the example below:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
  [unicoCheck setEnvironment:UAT];
```

{% endtab %}

{% tab title="Swift" %}

```swift
 unicoCheck.setEnvironment(.UAT);
```

{% endtab %}
{% endtabs %}

## Implementing the Callback Functions

Note that, as shown in the previous example, the implementation of the **`AcessoBioManagerDelegate`** interface mainly involves configuring the callback methods. Each method is called in a specific situation in the SDK's return process.

You simply need to override the methods demonstrated in the previous step with the business logic of your application:

{% stepper %}
{% step %}
**`onErrorAcessoBioManager(_ error: ErrorBio!)`**

This method is invoked when any implementation error occurs while using one of the methods, such as providing an incorrect document type for the document capture functionality.

When invoked, the method will receive a parameter of type `ErrorBio` that contains details of the error. For more information on the `ErrorBio` type, refer to the [error handling](https://devcenter.unico.io/idcloud-v2/by-client-integration/sdk/available-sdks/ios-sdk/error-handling-guide) article in this SDK documentation.

{% endstep %}

{% step %}
**`onUserClosedCameraManually()`**

This method is invoked whenever the user manually closes the camera, such as by clicking the "Back" button.

{% endstep %}

{% step %}
**`onSystemClosedCameraTimeoutSession()`**

This method is invoked as soon as the maximum session time is reached (without capturing any image).

{% hint style="warning" %}
It can be configured in the builder through the **setTimeoutSession** method. This method should receive the maximum session time in **seconds**. You can change the maximum session time for your user by using the face detection feature (Selfie camera with smart capture). If the time exceeds the duration specified for the process to capture the photo, you can display a customizable message or instruction to the user. The default value is **40 seconds**, and **the minimum value is also 40 seconds.**
{% endhint %}

{% endstep %}

{% step %}
**`onSystemChangedTypeCameraTimeoutFaceInference()`**

This method is invoked as soon as the maximum time for detecting a user's face is reached (without detecting anything). In this case, the camera mode is automatically switched to manual capture mode (without the intelligent capture silhouette).

{% hint style="warning" %}
The maximum capture time when using face detection (Selfie camera with smart capture) is **13 seconds**. If the user encounters any difficulty capturing the photo through face detection and exceeds the time specified in the process, the capture automatically switches to manual mode to facilitate the user's action **(TimeoutToFaceInference).**
{% endhint %}
{% endstep %}
{% endstepper %}

{% hint style="danger" %}
All the methods above must be created as indicated in your project (even without any logic). Otherwise, the project will not compile successfully.
{% endhint %}

## Configuring Camera Mode

The SDK has **intelligent framing** and automatic capture configured and enabled by default. As a result, you should configure the camera mode in your **builder** as follows:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
.m:
- (IBAction)configureSmartCamera:(UIButton *)sender {
   [unicoCheck setSmartFrame:true];
   [unicoCheck setAutoCapture:true];
}
```

{% endtab %}

{% tab title="Swift" %}

```kotlin
@IBAction func configureSmartCamera(_ sender: Any) {
    unicoCheck.setSmartFrame(true)
    unicoCheck.setAutoCapture(true)    
}
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
The false/true values for the methods above do not change the capture experience; they are only used for the internal logic of the SDK's functionality.
{% endhint %}

## Implementing Delegates for Camera Events

The camera opening method needs to know what to do when it successfully captures an image or encounters an error during the process. "**What to do**" is informed to the camera opening method through the configuration of delegates that are called in success or error situations.

By configuring the delegates, you can specify what happens in your app in error situations (method `onErrorSelfie`) or success (method `onSuccessSelfie`) when capturing images.

To configure the delegates, you need to implement the **`SelfieCameraDelegate`** and **`AcessoBioSelfieDelegate`** interfaces:

{% tabs %}
{% tab title="Objective-C" %}
{% code overflow="wrap" %}

```objectivec
.h:
#import <UIKit/UIKit.h>
#import <AcessoBio/AcessoBio.h>
#import "SelfieCameraDelegate.h"

@interface ViewController: UIViewController <AcessoBioManagerDelegate, SelfieCameraDelegate,
   AcessoBioSelfieDelegate> {
  AcessoBioManager *unicoCheck;
  // Your code from previous and next steps here
}
```

{% endcode %}
{% endtab %}

{% tab title="Swift" %}

```swift
import UIKit
import AcessoBio

class ViewController: UIViewController, AcessoBioManagerDelegate,
                      SelfieCameraDelegate, AcessoBioSelfieDelegate {    
  //Your code from previous and next steps here
}
```

{% endtab %}
{% endtabs %}

### **`onSuccessSelfie` Method**

When successfully capturing an image, this method is invoked and returns an object of type **`SelfieResult`**, which is later used in the REST API calls.

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
- (void)onSuccessSelfie:(SelfieResult *)result {
    NSLog(@"%@", result.base64);
} 
```

{% endtab %}

{% tab title="Swift" %}

```swift
func onSuccessSelfie(_ result: AcessoBio.SelfieResult!) {
    // Your code
 }
```

{% endtab %}
{% endtabs %}

The **`ResultCamera`** object returns 2 attributes: **`base64`** and **`encrypted`**:

* The **`base64`** attribute can be used if you want to display a preview of the image in your app.
* The **`encrypted`** attribute must be sent in the REST API calls of [by Client](https://devcenter.unico.io/idcloud-v2/by-client-integration/by-client-api/api-reference).

{% hint style="danger" %}

* The **`encrypted`** attribute is strictly intended for sending the image through the **by Client** APIs. It should not be opened or serialized, as its characteristics may change without prior notice. Its use should be exclusive in interactions with the APIs to ensure data integrity and security. **Unico is not responsible for any damages resulting from this practice, as modifications can occur unexpectedly.**
* The **`base64/encrypted`** files may vary in size depending on various factors, including the quality of the devices and photos generated by them, as well as Unico’s business rules. To avoid issues in your application, **do not limit the size of the string generated by the SDK for the files within your programming logic or infrastructure.**
  {% endhint %}

{% hint style="success" %}
If you want to convert the **base64** to bitmap, the standard method doesn’t work for iOS. You need to split the string starting from the comma (,) to make it work. To learn more, read this article: [How to convert a Base64 string into a Bitmap image to show it in an ImageView?](https://stackoverflow.com/questions/4837110/how-to-convert-a-base64-string-into-a-bitmap-image-to-show-it-in-a-imageview).
{% endhint %}

### `onErrorSelfie` Method

When an error occurs during the image capture, this method is invoked and returns an object of type **`ErrorBio`**:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
- (void)onErrorSelfie:(ErrorBio *)errorBio {
  // Your code
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
func onErrorSelfie(_ errorBio: ErrorBio!) {
  // Your code
 }
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Learn more about the types of **`ErrorBio`** in the SDK [error handling](https://devcenter.unico.io/idcloud-v2/by-client-integration/sdk/available-sdks/ios-sdk/error-handling-guide) section.
{% endhint %}

## Environment Configuration

{% hint style="info" %}
If not configured, the SDK uses the environment set through the configuration file (getHostKey). If getHostKey is not being used, an error will be returned.
{% endhint %}

It is possible to configure the environment to be used during the execution of the SDK. Use the `EnvironmentEnum` enumerated type, which contains the following values:

* **`EnvironmentEnum.PROD`**: for the Production environment
* **`EnvironmentEnum.UAT`**: for the Staging environment

See how to implement it in the example below:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
[unicoCheck setEnvironment:PROD];
```

{% endtab %}

{% tab title="Swift" %}

```swift
unicoCheck.setEnvironment(.PROD);
```

{% endtab %}
{% endtabs %}

## Prepare and Open Camera

To proceed with opening the camera, you must first prepare it using the `prepareSelfieCamera` method. This method takes as parameters the implementation of the `SelfieCameraDelegate` class and the JSON containing the credentials generated in the previous step.

{% tabs %}
{% tab title="Objective-C" %}
{% code overflow="wrap" %}

```objectivec
.h:
#import <UIKit/UIKit.h>
#import <AcessoBio/AcessoBio.h>
#import "SelfieCameraDelegate.h"

@interface ViewController: UIViewController <AcessoBioManagerDelegate,
SelfieCameraDelegate, AcessoBioSelfieDelegate> {
    AcessoBioManager *unicoCheck;
}

.m:
- (IBAction)openCamera:(UIButton *)sender {
    [[unicoCheck build] prepareSelfieCamera:self config:[YourUnicoConfigClass new]];
}
```

{% endcode %}
{% endtab %}

{% tab title="Swift" %}

```swift
import UIKit
import AcessoBio

class ViewController: UIViewController, AcessoBioManagerDelegate,
  SelfieCameraDelegate, AcessoBioSelfieDelegate {
    @IBAction func openCamera(_ sender: Any) {
        unicoCheck.build().prepareSelfieCamera(self, config: YourUnicoConfigClass())
    }
}
```

{% endtab %}
{% endtabs %}

Once the camera is prepared, the `onCameraReady` event is triggered and receives an object of type `AcessoBioCameraOpenerDelegate` as a parameter.

You should override this method and open the camera using the object received through the `open()` method:

{% tabs %}
{% tab title="Objective-C" %}

```objectivec
- (void)onCameraReady:(id)cameraOpener {
    [cameraOpener open:self];
}

- (void)onCameraFailed:(ErrorPrepare *)message {
    // Your code
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
func onCameraReady(_ cameraOpener: AcessoBioCameraOpenerDelegate!) {
    cameraOpener.open(self)
 }
 
func onCameraFailed(_ message: ErrorPrepare!) {
    // Your code
 }
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The The `ErrorPrepare` type is an extension of `ErrorBio`, thus containing all of its properties. Learn more about the `ErrorBio` type in the [error handling](https://devcenter.unico.io/idcloud-v2/by-client-integration/sdk/available-sdks/ios-sdk/error-handling-guide) section of the SDK.
{% endhint %}

If any error occurs while preparing the camera, the `onCameraFailed` event is triggered. You should implement this method applying your app's business rules.

### Monitoring Data Collection

The `prepareCamera` method provides an overload that accepts metadata to assist in identifying the user session and the flow. This is achieved via the `PrepareInfo` object, which consists of the following attributes:

* `externalUserId` (String, Required): User identifier within your system.
  * **Privacy**: To ensure sensitive data security, this value is automatically hashed using the SHA-256 algorithm before transmission.
* `useCase` (String, Optional): Identifier for the context or flow currently running (e.g., "account\_opening", "password\_recovery").
  * **Note**: This field is transmitted in plain text, without modification.

{% tabs %}
{% tab title="Objective-C" %}

```objective-c
.h:
#import <UIKit/UIKit.h>
#import <AcessoBio/AcessoBio.h>
#import "SelfieCameraDelegate.h"

@interface ViewController: UIViewController <AcessoBioManagerDelegate,
SelfieCameraDelegate, AcessoBioSelfieDelegate> {
    AcessoBioManager *unicoCheck;
}

.m:
- (IBAction)openCamera:(UIButton *)sender {
    PrepareInfo *prepareInfo = [[PrepareInfo alloc] 
        initWithExternalUserId:@"external_user_id" useCase:@"flow_id"];
    [[unicoCheck build] prepareSelfieCamera:self 
        config:[YourUnicoConfigClass new]
        prepareInfo:prepareInfo];
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
class ViewController: UIViewController, AcessoBioManagerDelegate,
  SelfieCameraDelegate, AcessoBioSelfieDelegate {
    @IBAction func openCamera(_ sender: Any) {
        let prepareInfo = PrepareInfo(
            externalUserId: "external_user_id",
            useCase: "use_case"
        )
        unicoCheck.build().prepareSelfieCamera(
            self, 
            config: YourUnicoConfigClass()),
            prepareInfo: prepareInfo
    }
}
```

{% endtab %}
{% endtabs %}

##

## Making a POST Request to the Client API

Capturing the images is only the first part of the journey. After capturing the image, it is necessary to send the `encrypted` generated by the SDK to the by Client REST APIs.

{% hint style="danger" %}
For security reasons, the time interval between the generation of the `encrypted` and its submission via one of the available flows must be no more than 10 minutes. Submissions made beyond this period will be automatically rejected by the API.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://devcenter.unico.io/unico-idcloud/by-client-integration/sdk/available-sdks/ios-sdk/usage-and-integration-guide/selfie-capture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
