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.
Whats 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:
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:
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:
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:
Step 2 - Install the dependencies
After updating your Podfile, open a terminal in your project's root directory and run:
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:
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:
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:
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:
Process details
Global configuration: defines the overall flow and appearance using
presentationOrder
andCafColorConfiguration
.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
(response
:CafUnifiedResponse
): returns the result after a successful session.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
: aCafUnifiedEvent.Error
event is triggered with a descriptive error message, allowing you to recover or notify the user.Cancelled
: aCafUnifiedEvent.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:
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:
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.
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:
Example of configuration chaining:
* 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) andlivenessBaseUrl
(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:
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.
Set the base URL
Use the
livenessBaseUrl
property to define the WSS endpoint.Example:
"wss://my.proxy.io/ws/"
Set the certificates
Use the
certificates
property to provide the SPKI hashes.Example:
["4d69f16113bed7d62ca56feb68d32a0fcb7293d3960="]
Code example:
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.
Set the Base URL
Use the
authBaseUrl
property to define the HTTPS endpoint.Example:
"https://my.proxy.io/v1/faces/"
Code example:
Configuration Structures
Caf Face Liveness
Customize the Face Liveness instruction screen.
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.
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.
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.
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
istrue
by default.instructionsConfig.enabled
istrue
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:
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:
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
.
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
.
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:
Message customization
Properties of CafMessageSettings
.
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:
Document capture flow
Properties of CafDocumentDetectorStep
.
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:
Upload customization
Properties of CafUploadSettings
.
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:
Proxy customizations
Properties of CafProxySettings
.
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:
Supported documents in Document Detector
Use these static values of CafDocument
:
.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:
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 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
andCafDocumentDetectorConfig
.
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
Replace standalone module initializers with
CafSDKProvider
Update enum cases to lowercase (e.g.,
.CNH_FRONT
→.cnhFront
)Use
CafDocumentDetectorStep(stepType:)
instead of legacy constructors
Last updated