Componente OCR (ModelOCR)
The SDK enables guided capture and automatic data extraction via optical character recognition (OCR) for official Mexican identification documents (INE, passport, etc.) in a fast and secure manner on the iOS platform.
When the OCR module is invoked, the SDK guides the user step-by-step:
- Instructions Screen: Visual and lighting recommendations to maximize capture quality.
- Guided, Intelligent Capture: Real-time detection of the document's obverse (front) and, if required, the reverse (back).
- Extraction and Validation: Automatic submission to and verification by Dicio services, returning control to the host application along with Base64 images and extracted data structured in JSON.
Compatibilidad y Requisitos
Installation via Swift Package Manager (SPM)
The SDK is distributed via Swift Package Manager.
Follow these steps to add it to your Xcode project:
Open your project in Xcode.
Go to the top menu and select File > Add Package Dependencies... (or select the project in the navigator, go to the Package Dependencies tab, and click the
+button).In the search bar at the top right, enter the Package repository URL:
Repositorio SPM
https://bitbucket.org/juarezsdco/dicioocr-packageConfigure the version rule to Up to Next Major Version and click Add Package.
In the product selection pop-up, select DicioOCR and ensure you assign it to your host app target (Host App).
Click Add Package to finish.
Prerequisites and Permissions
1. Camera Permission in Info.plist
The SDK requires access to the device's camera to scan documents. Add the NSCameraUsageDescription key to your application's Info.plist file or to the Info section of the target:
Info.plist
<key>NSCameraUsageDescription</key>
<string>Camera access is required to capture and validate your official ID.</string>
2. Importing the Module
In the Swift files where you intend to invoke the OCR flow, import the framework:
Import
import SwiftUI
import ModelOCRUI
Appearance Customization (DicioOCRUIConfig)
To customize the interface colors, button text, and institutional logos, the DicioOCRUIConfig structure is provided:
DicioOCRUIConfig
let ocrConfig = DicioOCRUIConfig(
loadLogo: "logoInstitucional", // Loading screen asset name
assetLogo: "logoInstitucional", // Scanner branding asset name
colorTitulo: "#4D21B2", // Hex color for main titles
colorSubTitulo: "#707070", // Hex color for subtitles and instructions
colorTextoBtn: "#FFFFFF", // Hex color for button text
colorFondoBtn: "#2B0877" // Hex color for button background
)
Detalle de Parámetros:
loadLogo(String): Name of the image resource located in your app'sAssets.xcassetsto be displayed during initial verification and loading.assetLogo(String): Name of the image resource inAssets.xcassetsfor branding within the scanning interface.colorTitulo(String): Hexadecimal color code (e.g.,#4D21B2) for interface titles.colorSubTitulo(String): Hexadecimal color code (e.g.,#707070) for subtitles and instructions.colorTextoBtn(String): Hexadecimal color code (e.g.,#FFFFFF) for text inside action buttons.colorFondoBtn(String): Hexadecimal color code (e.g.,#2B0877) for the background of interactive buttons.
- All colors must be specified in a valid hexadecimal format (
#RRGGBB). - The images assigned to
loadLogoandassetLogomust exist within the host project's asset catalog (Assets.xcassets).
Invocation of the Scan View (DicioOCRVCUI)
The component's main view is DicioOCRVCUI. To present it, you must provide the authentication token, the Dicio validation service URL, the visual configuration, and an instance conforming to the DicioScanOCRDelegate delegate.
Parámetros de Inicialización:
DicioOCRVCUI Init
DicioOCRVCUI(
token: "TOKEN_BEARER_PROPORCIONADO_POR_DICIO",
urlVerify: "https://api.devdicio.net:8444/v1/sec_dev_fintech_pagos_middleware",
config: ocrConfig,
delegateDicioOCR: self
)
token: Authorization Bearer token generated via the Dicio backend.urlVerify: Dicio service endpoint responsible for credential verification and dynamic license provisioning.config: Instance ofDicioOCRUIConfigcontaining the color scheme and logos.delegateDicioOCR: Object implementing theDicioScanOCRDelegateprotocol to receive callbacks and results.
Implementation of the DicioScanOCRDelegate protocol
The DicioScanOCRDelegate protocol handles image reception, the response containing extracted data, and control over closing the screen.
Protocolo DicioScanOCRDelegate
public protocol DicioScanOCRDelegate {
func imagesID(userIDPic: String, userIDFront: String, userIDBack: String)
func finishOCRView()
func ocrDicioResults(ocr: String, isSuccessfull: Bool, info: String, tipoID: String)
}
Métodos del Delegado:
1. imagesID
It executes once the ID capture completes successfully, returning the resulting images in Base64 format.
imagesID
func imagesID(userIDPic: String, userIDFront: String, userIDBack: String) {
// userIDPic: Base64 crop of the face photograph detected on the document
// userIDFront: Base64 image of the front of the document
// userIDBack: Base64 image of the back of the document
}
2. finishOCRView
It is invoked when the scanning flow finishes (whether successful, cancelled, or interrupted) so that the host application can close the modal view or navigate back.
finishOCRView
func finishOCRView() {
// In SwiftUI: change the presentation state (e.g., showOCR = false)
// In UIKit: self.dismiss(animated: true) or popViewController
}
3. ocrDicioResults
Returns the validation status and the JSON payload containing the data fields extracted from the document.
ocrDicioResults
func ocrDicioResults(ocr: String, isSuccessfull: Bool, info: String, tipoID: String) {
// ocr: JSON string containing all fields read from the document (front and back)
// isSuccessfull: Indicates whether the verification and scanning were successful
// info: Description or status message regarding the scan
// tipoID: Type of document detected (INE, Passport, etc.)
}
Result Data Structure (JSON)
The ocr parameter provided in ocrDicioResults contains a JSON structure with the readable data from the front and back sides:
Ejemplo Estructura JSON
{
"front": {
"nombreCompleto": "JUAN PEREZ LOPEZ",
"curp": "PELJ800101HDFRPR01",
"claveElector": "PELJ80010109H100",
"fechaNacimiento": "01/01/1980",
"sexo": "H",
"ineVigencia": "2030",
"emision": "2020"
},
"back": {
"cicMRZ": "123456789",
"seccionMRZ": "IDMEX1234567897<<1234<<<<<<<<<",
"identificadorCiudadano": "987654321"
}
}
Complete Integration Example in SwiftUI
Below is a comprehensive example of a SwiftUI implementation using a container with .fullScreenCover:
Ejemplo de Integración SwiftUI
import SwiftUI
import ModelOCRUI
struct HostScanView: View {
@State private var showOCRScanner = false
@State private var scanStatusMessage: String = "Presiona el botón para iniciar"
var body: some View {
VStack(spacing: 20) {
Text("Escaneo de Identificación")
.font(.title2)
.fontWeight(.bold)
Text(scanStatusMessage)
.font(.body)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal)
Button(action: {
showOCRScanner = true
}) {
Text("Escanear Identificación")
.font(.headline)
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.cornerRadius(12)
}
.padding(.horizontal, 30)
}
.fullScreenCover(isPresented: $showOCRScanner) {
let config = DicioOCRUIConfig(
loadLogo: "logoInstitucional",
assetLogo: "logoInstitucional",
colorTitulo: "#4D21B2",
colorSubTitulo: "#707070",
colorTextoBtn: "#FFFFFF",
colorFondoBtn: "#2B0877"
)
DicioOCRContainerView(
config: config,
token: "TOKEN_PROPORCIONADO_POR_DICIO",
urlVerify: "https://api.devdicio.net:8444/v1/sec_dev_fintech_pagos_middleware",
onFinish: { isSuccess, info in
showOCRScanner = false
scanStatusMessage = isSuccess ? "✅ Escaneo exitoso: \(info)" : "❌ Falló el escaneo: \(info)"
}
)
}
}
}
struct DicioOCRContainerView: View, DicioScanOCRDelegate {
let config: DicioOCRUIConfig
let token: String
let urlVerify: String
let onFinish: (_ isSuccess: Bool, _ info: String) -> Void
@State private var scanSuccessful: Bool = false
@State private var resultInfo: String = ""
// MARK: - DicioScanOCRDelegate
func imagesID(userIDPic: String, userIDFront: String, userIDBack: String) {
print("📸 [DicioOCR] Rostro Base64 recibido: \(userIDPic.prefix(30))...")
print("📸 [DicioOCR] Anverso Base64 recibido: \(userIDFront.prefix(30))...")
print("📸 [DicioOCR] Reverso Base64 recibido: \(userIDBack.prefix(30))...")
// Procesar o almacenar imágenes Base64 según sea requerido
}
func finishOCRView() {
print("🏁 [DicioOCR] Finalizando vista OCR")
onFinish(scanSuccessful, resultInfo)
}
func ocrDicioResults(ocr: String, isSuccessfull: Bool, info: String, tipoID: String) {
print("📋 [DicioOCR] Éxito: \(isSuccessfull) | Tipo ID: \(tipoID) | Info: \(info)")
print("📋 [DicioOCR] Payload JSON: \(ocr)")
self.scanSuccessful = isSuccessfull
self.resultInfo = info.isEmpty ? tipoID : info
}
var body: some View {
DicioOCRVCUI(
token: token,
urlVerify: urlVerify,
config: config,
delegateDicioOCR: self
)
.ignoresSafeArea()
}
}
Additional Considerations and Best Practices
- Manejo de Conectividad: The SDK features reactive network monitoring and retry support for temporary communication failures during token authentication or license provisioning.
- Gestión de Permisos: If the user does not grant camera permission, the SDK will automatically display an alert informing them of the need to enable such access in the iOS settings.
- Presentación en SwiftUI: It is recommended to present the
DicioOCRVCUIview using.fullScreenCover(isPresented:)and.ignoresSafeArea()to ensure optimal and continuous camera framing. - Seguridad de Credenciales: The verification token must be requested from your backend at runtime and should not be stored statically or exposed in the production code.