LogoLogo
Useful links
  • Home
  • Product guides
  • API
  • SDKs
  • Overview
  • First steps
  • ANDROID
    • Getting Started with the SDK
    • Standalone Modules
      • Document Detector
        • Release Notes
        • Current Version
        • Requirements
        • Gradle Dependencies
        • Gradle Source Code
        • Setting up the SDK
          • Setting properties
          • Capture Stages
          • Messages Settings
          • Customization
          • Security Settings
          • Detection Steps
          • Upload Mode
          • Advanced Settings
            • Proxy configuration
            • Preview configuration
        • Start Document Detection
        • Source Code
        • Google security form
        • Reduce SDKs size
        • SDKs response
        • References
        • FAQ
      • Face Liveness
        • Release Notes
        • Current Version
        • Requirements
        • Gradle Dependencies
        • Gradle Source Code
        • SDK Lifecycle
        • Building the SDK
        • Start Liveness Verification
        • Source Code
        • References
        • Advanced Features
        • FAQ
      • Face Authenticator
        • Release Notes
      • Smart Auth
        • Release Notes
        • Current Version
        • Requirements
        • Gradle Dependencies
        • Gradle Source Code
        • Permissions
        • SDK Lifecycle
        • Building the SDK
        • Start Smart Authentication
        • Source Code
        • References
        • FAQ
      • Face Liveness (deprecated)
        • Release Notes
  • iOS
    • Getting Started with the SDK
    • Standalone Modules
      • Document Detector
        • Release Notes
        • Current Version
        • Requirements
        • Installing the SDK
        • Setting up the SDK
          • Setting properties
          • Messages Settings
          • Customization
          • Detection Steps
          • Upload Mode
          • Advanced Settings
            • Proxy configuration
            • Preview configuration
        • Start Document Detection
        • References
        • FAQ
      • Face Liveness
        • Release Notes
        • Installation
        • Current Version
        • Requirements
        • SDK Lifecycle
        • Building the SDK
        • Start Liveness Verification
        • Source Code
        • References
        • FAQ
      • Face Authenticator
        • Release Notes
        • Installation
        • Current Version
        • Requirements
        • Building the SDK
        • Start the SDK
        • References
        • FAQ
      • Smart Auth
        • Release Notes
        • Installation
        • Current Version
        • Requirements
        • SDK Lifecycle
        • Building the SDK
        • Start Smart Authentication
        • Source Code
        • References
        • FAQ
      • Face Liveness (deprecated)
        • Release Notes
  • REACT NATIVE
    • Standalone Modules
      • Document Detector
        • Release Notes
        • Current Version
        • Requirements
        • Installation
        • Hooks
        • Start Document Verification
        • Source Code
        • TypeScript References
        • Customizing Style
        • FAQ
      • Face Liveness
        • Release Notes
        • Current Version
        • Requirements
        • Installation
        • Hooks
        • Start Liveness Verification
        • Source Code
        • TypeScript References
        • FAQ
      • Face Authenticator
        • Release Notes
        • Current Version
        • Requirements
        • Installation
        • Hooks
        • Start Authentication Verification
        • Source Code
        • TypeScript References
        • FAQ
      • Smart Auth
        • Getting started
        • Release notes
        • Using Native Modules
          • Requirements
          • Gradle Source Code
          • Podfile Source Code
          • Native Module Android
          • Native Module iOS
          • Import Native Modules
          • Source Code
          • TypeScript References
          • FAQ
        • Using Expo Modules
          • Requirements
          • Create Local Expo Module
          • Gradle Source Code
          • Podspec Source Code
          • Native Module Android
          • Native Module iOS
          • Import Expo Modules
          • Source Code
          • TypeScript References
          • FAQ
  • WEB (JAVASCRIPT)
    • Standalone Modules
      • Document Detector
        • Getting started
        • SDK builder options
          • Analytics
          • Appearance
          • Messages
        • SDK methods
        • Event listeners
        • Customization
        • Release notes
      • Face Liveness
        • Customization
        • Release notes
      • Face Authenticator
        • Customization
        • Release notes
      • Smart Auth
        • SDK errors
        • Customization
        • Release notes
LogoLogo

2025 © Caf. - All rights reserved

On this page
  • About CafSDK
  • What is Face Liveness
  • What is Document Detector
  • Get started with the SDK
  • Requirements to add
  • Steps to add
  • Via CocoaPods
  • How to initialize the SDK
  • Permissions
  • Configurations
  • Builder initialization
  • Completing a session
  • Important
  • Advanced flow
  • Dark Mode / Light Mode
  • Module-Specific configuration
  • Custom settings - Face Liveness
  • How it works
  • Custom settings
  • For Face Liveness (optional)
  • Authentication reverse proxy (optional)
  • Configuration Structures
  • Caf Face Liveness
  • Configuration instructions
  • Caf Color Configuration
  • Code example
  • More Information
  • Custom Settings - Document Detector
  • Document Detector configuration
  • Available Documents and Customization
  • How It Works
  • Custom configurations - Document Detector
  • Core configuration
  • Layout customization
  • Message customization
  • Document capture flow
  • Upload customization
  • Proxy customizations
  • Supported documents in Document Detector
  • Technical Support and Usage Tips
  • Release notes
  • CafSDK iOS v2.0.0
  • New Features
  • Breaking Changes
  • Migration Guide
  • CafSDK iOS v1.4.0
  • New Features
  • Documentation Updates
  • Configuration Enhancements
  • Breaking Changes
  • Migration Guide
  1. iOS

Getting Started with the SDK

About CafSDK

This technical documentation covers the implementation of CafSDK for IOS, detailing the configuration, initialization, execution of capture flows, and advanced customizations.

Currently, CafSDK integrates 2 main modules: Face Liveness (FL) and Document Detector (DD), executed sequentially with a unified configuration interface.

What is Face Liveness

It is the module that validates the authenticity of a face captured by a photo application, ensuring that the image corresponds to a real person.

Technical characteristics:

  • URL configuration for authentication (authBaseUrl) and liveness verification (livenessBaseUrl).

  • Flags to enable screen capture and debug mode.

  • Support for multiple authentication providers.

What is Document Detector

It is the module that enables the capture and processing of documents (e.g., ID card, social security card, passport, etc.).

Technical characteristics:

  • Configuration of a step-by-step flow defined by CafDocumentDetectorStep for document capture.

  • Operational parameters, such as timeout, manual capture flags, and other settings.

  • Possibility of using the camera for framing validations, or document file upload.


Get started with the SDK

Add the dependency

CafSDK supports integration via both Swift Package Manager (SPM) and CocoaPods, providing flexibility to choose the dependency manager that best suits your project. This guide explains the necessary steps to add CafSDK to your iOS project and provides details about the available modules.

Requirements to add

To use the CafSDK modules in iOS, ensure that your project meets the minimum requirements:

Requirement
Version

iOS Deployment Target

13.0+

Xcode

16.2+

Swift

5.10+

Note: configure your project's Info.plist with the necessary permissions for camera and network access.

Steps to add

Via Swift Package Manager (SPM)

Step 1 - Add the dependency

Open your project's Package.swift file and add the following dependency. This tells Swift Package Manager where to locate the CafSDK repository:

dependencies: [
    .package(url: "https://github.com/combateafraude/caf-ios-sdk.git", from: "2.0.0")
]

Step 2 - Include the desired products

After adding the dependency, include the necessary products in your application target. This allows you to integrate the full SDK or select only specific modules, according to your needs:

.target(
    name: "YourApp",
    dependencies: [
        .product(name: "CafSDK", package: "CafSDKiOS"),            // Full SDK
        .product(name: "DocumentDetector", package: "CafSDKiOS"),    // Only DocumentDetector
        .product(name: "CafFaceLiveness", package: "CafSDKiOS"),       // Only CafFaceLiveness
        .product(name: "IproovProvider", package: "CafSDKiOS"),        // Optional iProov provider
        .product(name: "FaceTec2DProvider", package: "CafSDKiOS")      // Optional FaceTec 2D provider
    ]
)

Additional information

  • Modularity: integrate only the necessary modules to keep your project lightweight.

  • Compatibility: the SDK is compatible with iOS 13.0+ and was developed with Swift 5.10+.

  • Version management: the dependency declaration of: "0.1.1" ensures the use of a compatible version. Always check the official repository for the latest version.

Via CocoaPods

Step 1 - Update your Podfile

To integrate CafSDK using CocoaPods, open your project's Podfile and add the following lines. This will instruct CocoaPods to download the necessary artifacts from the official repository:

# Full SDK
pod 'CafSDKiOS'

# Only DocumentDetector
pod 'CafSDKiOS/DocumentDetector'

# Only CafFaceLiveness
pod 'CafSDKiOS/CafFaceLiveness'

# Optional iProov provider
pod 'CafSDKiOS/IproovProvider'

# Optional FaceTec 2D provider
pod 'CafSDKiOS/FaceTec2DProvider'

Step 2 - Install the dependencies

After updating your Podfile, open a terminal in your project's root directory and run:

pod install

This command downloads and integrates all the specific modules into your project.

Additional Information

  • Selective integration: choose only the modules necessary for your project, optimizing performance.

  • Automatic dependency management: CocoaPods automatically manages version resolution and dependency conflicts.

  • Documentation and support: for more detailed instructions or troubleshooting, consult the CafSDK documentation.


How to initialize the SDK

This guide explains how to initialize the CafSDK on iOS. It covers the requirements, permissions, global configuration, module-specific configuration, and builder initialization.

Permissions

For the SDK modules to function correctly, you must declare the following permissions in your Info.plist:

For Face Liveness:

  • Camera Usage Description (NSCameraUsageDescription): explains why the application needs camera access for face detection.

  • Network access: no explicit permission is required, but ensure your application supports secure connections (HTTPS/WSS).

For Document Detector:

  • Camera Usage Description (NSCameraUsageDescription): required to capture document images.

  • Photo Library Usage Description (NSPhotoLibraryUsageDescription): required if your application supports sending images from the library (optional).


Configurations

The initialization process is divided into 2 parts: global configuration and module-specific configuration.

Global configuration

Create a CafSDKConfiguration object, which serves as the central container for all configurations. This configuration defines the execution order of the modules and the visual identity (through a color configuration).

Code example:

let sdkConfig = CafSDKConfiguration(
    presentationOrder: [.faceLiveness, .documentDetector] // Required
)

Module-Specific configuration

After the global configurations, configure each module individually to adjust the operational, security and visual parameters.

Document Detector configuration

Configure the Document Detector module by specifying the capture flow and options such as manual capture and pop-up confirmations.

Code example:

sdkConfig.setDocumentDetectorConfig(CafDocumentDetectorConfig(
    flow: [CafDocumentDetectorStep(stepType: .cnhFull)] // Required for document detector flow
))

Face Liveness configuration

Configure the Face Liveness module to validate that the captured face belongs to a living person. Define options for loading indicators, endpoints and security certificates.

Code example:

sdkConfig.setFaceLivenessConfig(CafFaceLivenessConfig())

Builder initialization

Builder initialization is the step where the CafSDK capture flow is configured for execution. Use CafSdkProvider.Builder to provide the necessary parameters, including a mobile token, person ID, environment, and the unified callback to handle events.

Code example:

// Create the SDK configuration with the desired modules and custom settings
var sdkConfig = CafSDKConfiguration(
        presentationOrder: [.faceLiveness, .documentDetector]
    ).setDocumentDetectorConfig(CafDocumentDetectorConfig(flow: [CafDocumentDetectorStep(stepType: .cnhFront)])) // Example required document
        .setFaceLivenessConfig(CafFaceLivenessConfig())

// Build the SDK with required parameters and a callback for events
let builder = CafSDKProvider.Builder(
    self,
    mobileToken: "yourToken",
    personId: "personId",
    environment: .prod,
    configuration: sdkConfig,
    callback: { [weak self] event in
        self?.handleUnifiedEvent(event)
    }
)
let sdk = builder.build()

// Start the SDK session
sdk.start()

// Example unified event handler
private func handleUnifiedEvent(_ event: CafUnifiedEvent) {
    DispatchQueue.main.async { [weak self] in
        guard let self = self else { return }
        switch event {
        case .loading:
            print("🔄 Loading...")
        case .loaded:
            print("🔄 Loaded")
        case .success(let responses):
            responses.forEach { response in
                print("Module: \(response.moduleName) Result: \(response.result)")
            }
        case .error(let message):
            print("❌ Error:\n\(message)")
        case .cancelled:
            print("⚠️ Cancelled")
        case .log(let level, let message):
            print("[\(level)] \(message)")
        }
    }
}

Process details

  • Global configuration: defines the overall flow and appearance using presentationOrder and CafColorConfiguration.

  • Module-specific configuration: customizes the Document Detector and Face Liveness modules with individual settings (e.g., capture flow, loading indicator, API endpoints).

  • Initialization with the Builder: the builder pattern gathers all the necessary parameters (mobile token, person ID, environment, configuration, and callback) to create and start the SDK.

Following these steps, your iOS project will be correctly configured to use CafSDK, ensuring a robust and efficient integration of the document detection and face verification modules.


Completing a session

A complete session in CafSDK covers the entire flow, from initialization to completion - whether this completion is a successful validation, an error, or a cancellation by the user.

Session event handling

The builder's callback returns a set of events defined by the CafUnifiedEvent enumeration. These events include:

  • Loading: indicates that the SDK is processing.

  • Loaded: notifies that all modules are ready.

  • Success (responses: [CafUnifiedResponse]): returns results after all modules complete when waitForAllServices is enabled.

  • Error (message: String): provides an error message if something goes wrong.

  • Cancelled: indicates that the session was canceled by the user.

  • Log (level: CafLogLevel, message: String): offers detailed log information.

Important

A session is considered complete when all modules in the capture flow have finished their operation successfully or when the process is interrupted by an error or a cancellation by the user. In a complete session:

Full execution

Each module that finishes successfully sends a Success event, including:

  • moduleName: identifies the module (e.g., "documentDetector" or "faceLiveness") that completed the operation.

  • result: a map ([String: Any]) that contains the module execution data (such as captured images or validation results).

Interrupted flow

If an error occurs or the user cancels the process:

  • Error: a CafUnifiedEvent.Error event is triggered with a descriptive error message, allowing you to recover or notify the user.

  • Cancelled: a CafUnifiedEvent.Cancelled event is activated, which allows you to clear resources or present a cancellation message.

Event Handling Example

Check out an example of how to handle these events in the unified callback for iOS:

func handleUnifiedEvent(_ event: CafUnifiedEvent) {
    switch event {
    case .loading:
        // Show a loading indicator
        break
    case .loaded:
        // Update UI to show that modules are ready
        break
    case .success(let responses):
        // Process all successful responses
        responses.forEach { response in
            print("Module: \(response.moduleName) Result: \(response.result)")
        }
    case .error(let message):
        // Handle error state (display an alert, retry, etc.)
        print("Error: \(message)")
    case .cancelled:
        // Handle cancellation gracefully
        break
    case .log(let level, let message):
        // Log internal messages for debugging purposes
        print("[\(level)] \(message)")
    }
}

Summary

  • Complete session: a session is considered complete when all configured modules finish their tasks successfully, or when an error/cancellation occurs.

  • Centralized management: The unified callback ensures that, regardless of the outcome, your application will be notified and can take the appropriate action.

This approach ensures robust integration with CafSDK, efficiently handling each state of the capture flow, from start to finish.


Advanced flow

This section explains how to customize and adjust the CafSDK capture flow to meet specific business requirements and enhance the user experience on iOS.

Module execution order

The order in which modules are executed is defined by the presentationOrder field of the CafSDKConfiguration object. This sequence is crucial, as it directly impacts the flow logic. For example, if the process requires the document to be captured before facial validation, the order must reflect this priority.

Code example:

let sdkConfig = CafSDKConfiguration(
    presentationOrder: [.documentDetector, .faceLiveness],
    colorConfig: CafColorConfiguration(
        primaryColor: "#FF0000",
        secondaryColor: "#FFFFFF",
        contentColor: "#FF0000",
        backgroundColor: "FFFFFFF",
        mediumColor: "00FF00"
    ), // Optional
    waitForAllServices: true // Optional
)

Dark Mode / Light Mode

Dark Mode support is enabled by default in the SDK to ensure a consistent user experience across system themes. However, if you want to apply a custom color scheme, they must first check whether the device is currently using Dark Mode or Light Mode, and configure the CafColorConfiguration accordingly.

Use the system’s interface style to determine the current mode, then adjust the color configuration to match the desired appearance.

let userInterfaceStyle = UITraitCollection.current.userInterfaceStyle

let colorConfig: CafColorConfiguration

if userInterfaceStyle == .dark {
    colorConfig = CafColorConfiguration(
        primaryColor: "#FFFFFF",
        secondaryColor: "#222222",
        contentColor: "#FFFFFF",
        backgroundColor: "#000000",
        mediumColor: "#555555"
    )
} else {
    colorConfig = CafColorConfiguration(
        primaryColor: "#FF0000",
        secondaryColor: "#FFFFFF",
        contentColor: "#FF0000",
        backgroundColor: "#FFFFFF",
        mediumColor: "#00FF00"
    )
}

let sdkConfig = CafSDKConfiguration(
    presentationOrder: [.documentDetector, .faceLiveness],
    colorConfig: colorConfig
)

Module-Specific configuration

Customize individual modules using the setDocumentDetectorConfig and setFaceLivenessConfig methods. These methods allow you to adjust essential parameters, such as:

  • Capture timeout: defines the maximum time for manual capture.

  • Request timeout: sets the maximum wait time for a service response.

  • Debugging flags: enable or disable debugging modes to identify issues during development.

  • Layout and other settings: adjust visual and operational parameters specific to each module.

Visual customization

With the CafColorConfiguration object, you can align the visual identity of the capture flow with your application's design. This ensures that visual elements (buttons, backgrounds, and indicators) are consistent with your brand identity.

Log Registration and Monitoring

The unified callback implements different log levels (DEBUG, USAGE, INFO), allowing detailed monitoring of each step in the flow. These logs are essential for integration with monitoring tools, performance tuning, and real-time issue detection.

Example in the callback:

callback = { event in
    switch event {
    case .log(let level, let message):
        // Log messages for detailed monitoring of the flow
        print("[LOG] \(level): \(message)")
    default:
        break
    }
}

Example of configuration chaining:

var sdkConfig = CafSDKConfiguration(
    presentationOrder: [.faceLiveness, .documentDetector],
    colorConfig: CafColorConfiguration(
        primaryColor: "#FF0000",
        secondaryColor: "#FFFFFF",
        contentColor: "#FF0000",
        backgroundColor: "FFFFFFF",
        mediumColor: "00FF00"
    )
)
.setDocumentDetectorConfig(CafDocumentDetectorConfig(
    flow: [CafDocumentDetectorStep(stepType: .cnhFull)]
))
.setFaceLivenessConfig(CafFaceLivenessConfig())

* By chaining these configuration calls, you can precisely control the behavior and appearance of each module in the unified flow.


Custom settings - Face Liveness

The Face Liveness module in CafSDK offers robust measures to ensure that the user's face is real and belongs to a living person. It supports multiple providers, such as iProov and FaceTec2D, allowing you to choose or combine solutions based on your requirements.

For detailed customization options, see: Face Liveness Configurations.

To configure Face Liveness

The main configuration object is CafFaceLivenessConfig, which includes:

  • Instruction configuration: customizable instructions and steps (via CafInstructionsConfiguration) that guide the user.

  • Loading indicator: a flag (loadingEnabled) to display a loading indicator during processing.

  • Endpoint URLs (optional): authBaseUrl (HTTPS) and livenessBaseUrl (WSS) for API communication when using a reverse proxy.

  • Certificates (optional): a list of SHA-256 SPKI encoded base64 hashes for secure communication over WSS, required only when using a reverse proxy.

Configuration example:

sdkConfig.setFaceLivenessConfig(CafFaceLivenessConfig(
    instructionsConfig: CafInstructionsConfiguration(
        enabled: true,
        title: "Scan Your Face",
        descriptionText: "Follow these steps:",
        steps: ["Hold the phone steady", "Ensure good lighting"],
        buttonTitle: "Start Scan",
        headerImage: UIImage(named: "scan_icon")
    ),
    loadingEnabled: true,
    authBaseUrl: "https://my.proxy.io/v1/faces/", // Optional, only used with reverse proxy
    livenessBaseUrl: "wss://my.proxy.io/ws/", // Optional, only used with reverse proxy
    certificates: ["4d69f16113bed7d62ca56feb68d32a0fcb7293d3960="] // Optional, only used with reverse proxy
))

How it works

When faceLivenessConfig is set in your CafSDKConfiguration, the Face Liveness module will automatically execute when its position in the presentation order is reached. After successful execution, a CafUnifiedEvent.Success event is triggered, containing:

  • moduleName: the module identifier (e.g., "faceLiveness").

  • result: a dictionary ([String: Any]) containing the data resulting from the liveness check.

These results can then be processed in your unified callback to update the UI or proceed with your application's flow.


Custom settings

SDK configuration summary

The SDK is configured via CafSDKConfiguration, which includes settings for:

  • UI customization (colors, instructions, and images).

  • Reverse proxy endpoints and security certificates (optional).

  • Optional parameters like personId.

Reverse Proxy Configuration

For Face Liveness (optional)

Use this configuration only if you're routing Face Liveness requests through a reverse proxy.

Requirements:

  • Protocol: wss:// (WebSocket Secure).

  • Certificates: Base64-encoded SHA-256 hashes of the certificate's Subject Public Key Info (SPKI).

Configuration:

All reverse proxy settings for Face Liveness are defined using the CafFaceLivenessConfig structure.

  1. Set the base URL

    • Use the livenessBaseUrl property to define the WSS endpoint.

    • Example: "wss://my.proxy.io/ws/"

  2. Set the certificates

    • Use the certificates property to provide the SPKI hashes.

    • Example: ["4d69f16113bed7d62ca56feb68d32a0fcb7293d3960="]

Code example:

.setFaceLivenessConfig(CafFaceLivenessConfig(
    livenessBaseUrl: "wss://my.proxy.io/ws/", // Optional, only used with reverse proxy
    certificates: ["4d69f16113bed7d62ca56feb68d32a0fcb7293d3960=",
                   "50f71c5dda30741ee4be1ac378e12539b0d1d511f99=",
                   "9f85e26c1ae41f7ac97adc4099be7f2a40759510ab9="] // Optional, only used with reverse proxy
))

Authentication reverse proxy (optional)

Use this configuration only if you're routing authentication requests through a reverse proxy.

Requirement:

  • Protocol: https://

Configuration:

All reverse proxy settings for authentication are defined using the CafFaceLivenessConfig structure.

  1. Set the Base URL

    • Use the authBaseUrl property to define the HTTPS endpoint.

    • Example: "https://my.proxy.io/v1/faces/"

Code example:

.setFaceLivenessConfig(CafFaceLivenessConfig(
    authBaseUrl: "https://my.proxy.io/v1/faces/" // Optional, only used with reverse proxy
))

Configuration Structures

Caf Face Liveness

Customize the Face Liveness instruction screen.

Property
Type
Description
Default

loadingEnabled

Bool

Enables/disables the loading screen.

true

authBaseUrl

String

HTTPS URL for authentication requests. Optional. Required only for reverse proxy.

""

livenessBaseUrl

String

WSS URL for FaceLiveness WebSocket. Optional. Required only for reverse proxy.

""

certificates

[String]

Base64-encoded SHA-256 SPKI hashes. Optional. Required only for WSS via proxy.

[]

instructionsConfig

CafInstructionsConfiguration

Customize instructions screen (title, steps, images).

See below

Configuration instructions

Customize the Face Liveness instruction screen.

Property
Type
Description
Default

enabled

Bool

Show/hide the instructions screen.

true

title

String?

Header title (e.g., "Face Scan Instructions").

nil

descriptionText

String?

Brief description (e.g., "Follow these steps").

nil

steps

[String]?

Ordered list of instructions (e.g., ["Step 1", "Step 2"]).

nil

buttonTitle

String?

Text for the confirmation button (e.g., "Start Scan").

nil

headerImage

UIImage?

Image displayed at the top of the screen.

nil

Caf Color Configuration

Personalize the interface.

Property
Type
Description
Format

primaryColor

String

Primary buttons, highlights.

Hex code (e.g., #FF0000)

secondaryColor

String

Secondary elements, borders.

Hex code

contentColor

String

Text and icons.

Hex code

backgroundColor

String

Screen background.

Hex code

mediumColor

String

Neutral elements (e.g., progress bars).

Hex code

Code example

Complete Configuration Code Example.

var facelivenessConfig = CafFaceLivenessConfig(
        instructionsConfig: CafInstructionsConfiguration(
            enabled: true,
            title: "Scan Your Face",
            descriptionText: "Follow these steps:",
            steps: ["Hold the phone steady", "Ensure good lighting"],
            buttonTitle: "Start Scan",
            headerImage: UIImage(named: "scan_icon")
        ), loadingEnabled: true,
        authBaseUrl: "https://my.proxy.io/v1/faces/",
        livenessBaseUrl: "wss://my.proxy.io/ws/",
        certificates: ["4d69f16113bed7d62ca56feb68d32a0fcb7293d3960="]
    )

More Information

Certificate Requirements

  • Certificates must be the base64-encoded SHA-256 hash of the certificate's Subject Public Key Info (SPKI).

Protocol Application

  • The Face Liveness URL must use wss:// when using a reverse proxy.

  • The Authentication URL must use https:// when using a reverse proxy.

Default Values

  • loadingEnabled is true by default.

  • instructionsConfig.enabled is true by default.


Custom Settings - Document Detector

The DocumentDetector module uses machine learning (via TensorFlow Lite) to securely detect and validate documents. This module is highly configurable, allowing you to define custom document flows, preview screens, and manual capture settings.

Document Detector configuration

The main configuration object for this module is the CafDocumentDetectorConfig, which offers options such as:

  • Flow: An array of CafDocumentDetectorStep objects to determine the order and type of document captures.

  • Layout Customization: Define the appearance of the capture interface using the DocumentDetectorLayout class.

  • Upload Settings: Control file format, compression, and maximum file size with CafUploadSettings.

  • Manual Capture Options: Enable manual capture, adjust the timeout, and configure preview details (such as title, subtitle, confirmation, and attempt labels).

  • Proxy and Timeout Settings: Configure a proxy and adjust the network timeout for secure document uploads (optional).

Code example:

let documentConfig = CafDocumentDetectorConfig(
    flow: [/* Array of CafDocumentDetectorStep items */], // Required
    layout: DocumentDetectorLayout(),
    uploadSettings: CafUploadSettings(enable: true),
    manualCaptureEnabled: true,
    manualCaptureTime: 45,
    requestTimeout: 60,
    showPopup: true
)

Available Documents and Customization

CafSDK provides a set of pre-configured documents (e.g., rgFront, cnhFront, passport, etc.). You can customize these documents or create your own flows by adjusting the properties of each CafDocumentDetectorStep and CafDocument.

How It Works

When documentConfig is set in your CafSDKConfiguration, the Document Detector module automatically runs when it reaches its designated position in the flow.

After a successful execution, a CafUnifiedEvent.Success event is triggered, containing:

  • result: A dictionary ([String: Any]) with the captured document data.

  • moduleName: The module identifier (e.g., "documentDetector").

These results are then processed in your unified call response, allowing you to proceed with the flow or store the captured information as needed.

Code example:

sdkConfig.setDocumentDetectorConfig(CafDocumentDetectorConfig(
    flow: [CafDocumentDetectorStep(stepType: .rgFront)],
    manualCaptureEnabled: true,
    manualCaptureTime: 45,
    requestTimeout: 60,
    showPopup: true
))

After the document capture and processing are completed, the Document Detector module triggers a CafUnifiedEvent.Success event, which includes:

  • moduleName: The module identifier (e.g., "documentDetector").

  • result: The captured document data.


Custom configurations - Document Detector

To configure the Caf Document Detector, use the CafDocumentDetectorConfig structure, which includes:

  • Document capture flow steps.

  • User interface (UI) layout customization.

  • Feedback messages.

  • Upload behavior.

  • Proxy settings.

Core configuration

Properties of CafDocumentDetectorConfig .

Property
Type
Description
Default

flow

[CafDocumentDetectorStep]

Ordered list of document capture steps.

[]

layout

DocumentDetectorLayout

UI customization (colors, buttons, fonts).

Default layout

uploadSettings

CafUploadSettings

Controls document upload behavior.

enable: false

manualCaptureEnabled

Bool

Enables manual capture button.

true

manualCaptureTime

TimeInterval

Timeout (seconds) for manual capture.

45

requestTimeout

TimeInterval

HTTP request timeout.

60

showPopup

Bool

Shows/hides the initial instruction popup.

true

proxySettings

CafProxySettings?

Reverse proxy configuration (host, port, auth).

nil

previewShow

Bool

Enables post-capture preview screen.

false

previewTitle

String?

Title text on preview screen.

nil

previewSubtitle

String?

Subtitle text on preview screen.

nil

previewConfirmLabel

String?

Text for the confirmation button on preview.

nil

previewRetryLabel

String?

Text for the retry button on preview.

nil

messageSettings

CafMessageSettings

Customizable feedback messages.

Default messages

enableMultiLanguage

Bool

Enables auto-translation of default messages.

true

allowedPassportCountryList

[CafCountryCodes]?

Whitelist of allowed passport countries (e.g., .BR, .US).

nil

selectDocumentConfig

CafSelectDocumentConfig?

Configures document selection screen (title/description)

nil

currentStepDoneDelay

TimeInterval

Delay (in seconds) before proceeding after completing a capture step

1.0

Layout customization

Properties of DocumentDetectorLayout .

Property
Type
Description
Default

closeButtonImage

UIImage?

Image for the close button.

System default

closeButtonColor

UIColor?

Color of the close button.

Primary color

closeButtonSize

CGFloat?

Size (width/height) of the close button.

44

closeButtonContentMode

UIView.ContentMode?

Content mode for the close button image.

.scaleAspectFit

uploadBackGroundColor

UIColor

Background color during upload.

Primary color

previewBackGroundColor

UIColor

Background color for preview screen.

.white

primaryColor

UIColor

Color for buttons/progress indicators.

#34D690 (green)

feedbackColors

DocumentFeedbackColors

Colors for feedback overlays (default/error/success).

Predefined colors

font

String?

Custom font name (e.g., "Avenir-Bold").

System font

Code example:

let layout = DocumentDetectorLayout()
layout.closeButtonImage = UIImage(named: "close_icon")
layout.primaryColor = .blue
layout.font = "Helvetica-Bold"
layout.feedbackColors = DocumentFeedbackColors(
    defaultColor: .gray, 
    errorColor: .red, 
    successColor: .green
)

Message customization

Properties of CafMessageSettings .

Property
Description
Default Value

waitMessage

Shown during SDK initialization.

"Aguarde" (Waiting)

fitTheDocumentMessage

Advises aligning document to the mask.

"Encaixe o documento na marcação"

verifyingQualityMessage

Shown during quality check.

"Verificando qualidade…"

lowQualityDocumentMessage

Shown on capture failure.

"Ops, tente novamente"

sensorLuminosityMessage

Low brightness warning.

"Ambiente muito escuro"

sensorOrientationMessage

Device orientation warning.

"Celular não está na horizontal"

aiScanDocumentMessage

Prompt to scan a document.

"Escaneie um documento"

aiGetCloserMessage

Prompt to move closer.

"Se aproxime do documento"

aiCapturedMessage

Confirmation of successful capture.

"Capturando o documento"

Full list: 20+ messages. Use .set[MessageName](message: String) for customize any text.

Code example:

var messages = CafMessageSettings()
    messages = messages.setWaitMessage("Please Wait..")

Document capture flow

Properties of CafDocumentDetectorStep.

Property
Type
Description
Required

stepType

CafDocument

Document type to capture (e.g., .rgFront).

Yes

customStepLabel

String?

Text shown at the bottom of the screen.

No

customIllustration

UIImage?

Image shown in the instruction popup.

No

showStepLabel

Bool

Toggles visibility of the step label.

No (true)

Code example:

    let step = CafDocumentDetectorStep(
        stepType: .rgFront,
        customStepLabel: "Front of ID",
        customIllustration: UIImage(named: "id_front_icon")
    )

Upload customization

Properties of CafUploadSettings.

Property
Type
Description
Default

enable

Bool

Enables document upload functionality.

false

compress

Bool

Compresses files before upload.

true

fileFormats

[FileFormat]

Allowed formats: .png, .jpeg, .pdf.

All formats

maximumFileSize

Int

Max file size in KB.

10000 (10MB)

Code example:

let uploadSettings = CafUploadSettings(
    enable: true,
    fileFormats: [.jpeg, .pdf],
    maximumFileSize: 5000
)

Proxy customizations

Properties of CafProxySettings.

Property
Type
Description
Required

hostname

String

Proxy host (e.g., "proxy.com").

Yes

port

Int

Proxy port (e.g., 8080).

Yes

user

String?

Authentication username.

No

password

String?

Authentication password.

No

Code example:

let proxy = CafProxySettings(hostname: "my.proxy.io", port: 443)

Supported documents in Document Detector

Use these static values of CafDocument:

Document Type
Description

.rgFront

Front of Brazilian ID (RG)

.rgBack

Back of Brazilian ID (RG)

.rgFull

Brazilian ID (opened, showing front and back)

.cnhFront

Front of Brazilian Driver's License (CNH)

.cnhBack

Back of Brazilian Driver's License (CNH)

.cnhFull

Brazilian Driver's License (opened)

.crlv

Brazilian Vehicle Registration (CRLV)

.rneFront

Front of Brazilian Foreigner ID (RNE)

.rneBack

Back of Brazilian Foreigner ID (RNE)

.ctpsFront

Front of Brazilian Work Card (CTPS)

.ctpsBack

Back of Brazilian Work Card (CTPS)

.passport

Passport (any country)

.any

Generic document (no specific validation)

Note: All enum cases are now in lowercase (e.g., use .rgFront instead of .RG_FRONT)

Code example:

let layout = DocumentDetectorLayout()
layout.primaryColor = .blue
layout.closeButtonImage = UIImage(named: "close")

var messages = CafMessageSettings()
    messages = messages.setWaitMessage("Please Wait..")

let config = CafDocumentDetectorConfig(
    flow: [
        CafDocumentDetectorStep(stepType: .rgFront),
        CafDocumentDetectorStep(stepType: .rgBack)
    ],
    layout: layout,
    uploadSettings: CafUploadSettings(enable: true),
    proxySettings: CafProxySettings(hostname: "proxy.example.com", port: 8443),
    messageSettings: messages
)

Technical Support and Usage Tips

For more details and advanced usage scenarios, refer to the following resources:

  • FAQs and Troubleshooting: check our FAQ section for common issues and troubleshooting tips.

  • Support: for additional assistance, contact our support team or join our developer community forum.

We continuously update the documentation as new features and improvements are released. Stay up to date for future updates!


Release notes

CafSDK iOS v2.0.0

New Features

  • Batch Results Flag: CafSDKConfiguration(waitForAllServices: true) now aggregates all module responses into a single .success(responses: [...]).

  • Unified .success Update: .success now always carries an array of responses.

Breaking Changes

  • Signature of CafUnifiedEvent.success changed to success(responses: [CafUnifiedResponse]).

Migration Guide

  1. Update to v2.0.0+.

  2. Change handler to expect an array:

    case .success(let responses):
        responses.forEach { resp in /* ... */ }

CafSDK iOS v1.4.0

New Features

  • Introducing CafSDKProvider: A unified entry point for integrating Face Liveness and Document Detector modules with a single configuration.

  • Builder Pattern: Simplified initialization using CafSDKProvider.Builder for modular, type-safe setup.

  • Unified Configuration: Configure both modules using CafSDKConfiguration, including execution order (presentationOrder) and UI theming (CafColorConfiguration).

  • Cross-Module Consistency: Shared authentication, environment, and logging across modules.

Documentation Updates

  • Revised guides for Swift Package Manager (SPM) and CocoaPods integration.

  • Added detailed examples for CafFaceLivenessConfig and CafDocumentDetectorConfig.

Configuration Enhancements

Face Liveness

  • Customize instructions (CafInstructionsConfiguration).

  • Configure reverse proxy endpoints (authBaseUrl, livenessBaseUrl).

Document Detector

  • Define multi-step capture flows ([CafDocumentDetectorStep]).

  • UI customization (CafDocumentDetectorLayout, CafMessageSettings).

  • Proxy support (CafProxySettings).

Breaking Changes

  • New integration Module: CafSDK

  • Module Renaming: FaceLiveness → CafFaceLiveness, DocumentDetector → CafDocumentDetector

  • Updated Dependencies: Requires Xcode 16.2+ and iOS 13.0+

Migration Guide

  1. Replace standalone module initializers with CafSDKProvider

  2. Update enum cases to lowercase (e.g., .CNH_FRONT → .cnhFront)

  3. Use CafDocumentDetectorStep(stepType:) instead of legacy constructors

Last updated 2 days ago

CAF Mobile Token: valid

Consult:

Consult:

Consult: and

GitHub Repository: access the source code, issue tracking, and release notes in the .

CAF mobileToken
CafSDK GitHub repository
DocumentDetector
FaceLiveness
DocumentDetector
FaceLiveness