TrustVision SDK is an iOS SDK for TrustVision Engine. It provides these features:
Adding *. framework and *.bundle by "Add Files to {your_name_project}"

Note: Set up the optional status for TrustVisionNFC.xcframework
<key>NSCameraUsageDescription</key>
<string>Open camera</string>
pod 'TensorFlowLiteSwift', '2.11.0'
pod 'PromiseKit', '6.8'
pod 'OpenSSL-Universal', '1.1.2301' # if you are using module NFC
pod 'CryptoSwift', '1.7.1'
post_install do |installer|
installer.pods_project.targets.each do |target|
// If when compiling your project, "Undefined symbol" occurs, please add the module name which is having the error here
// add OpenSSL-Universal if you are using module NFC
if ['TensorFlowLiteC', 'TensorFlowLiteSwift', 'PromiseKit', 'OpenSSL-Universal', 'CryptoSwift'].include? "#{target}"
target.build_configurations.each do |config|
config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
end
end
end
end
If not, add manually:
Embed & SignCocoaLumberjack.frameworkPromiseKit.frameworkDo Not EmbedTensorFlowLite.frameworkTensorFlowLiteC.frameworkValidate Workspace in Build SettingsIf host app is using Objective-C, please follow these additional steps:
SWIFT_VERSION)-lc++ and -ObjC in Other linker flagsMethod 1: Highly recommended:
let initConfiguration = TVInitializeConfigurationBuilder()
.setAccessKeyId("accessKey")
.setAccessKeySecret("secretKey")
.setBaseUrl("endpoint")
.setClientSettingsJsonString(nil)
.setClientSettings(nil)
.setFlowId(nil)
.setLanguageCode(nil)
.setSslCertificates(nil)
.setXRequestId(nil)
.setXRequestId2(nil)
.setEnableDebuggingLog(false)
.setImageEncryptionKey(nil)
.setSecurityPublicKey(nil)
.setHeaders(nil)
.setEnableGetClientSetting(true)
.setLogServerAccess("accessKey for log event")
.setLogServerSecret("secretKey for log event")
.setLogServerBaseUrl("endpoint for log event")
.build()
TrustVisionSdk.shared.initialize(
config: initConfiguration,
success: {
// sdk is initialized
}, failure: { (error) in
// sdk is failed to initialize
}) { (event) in
// sdk is initialized with event
}
Options:
String?. The access key id of the server.String?. The secret key of the server.String?. The endpoint of the server.String?. The client setting.
It's the setting specialized for each client from TS server.
It's the response json string get by API https://ekyc.trustingsocial.com/api-reference/customer-api/#get-client-settings.
When it's null or unmatched with the expected type then the default setting in the SDK will be used.TVClientSettingsResponse?. The client setting, same with setClientSettingsJsonString(), but in Object type instead of JSON string.String?, parameter to get client setting. Default is null| Value | Flow |
|---|---|
face_authen | Face Authen |
onboarding | Onboarding |
String?. Language code. vi or en[TVCertificate?]?. List of init SSL pining certificate filesString?. For image encrypt. Set nil to ignore encryptionString?. For public key. Set nil to use it default in TSString? https://ekyc.trustingsocial.com/api-reference/customer-api#api-reconciliationString? another xRequestId[String :String?]?. The headers to be added to the request.Bool, default is true. It allows the SDK to retrieve client settings internally when in Full mode. If set to false, please provide client settings using setClientSettings or setClientSettingsJsonString.String. The access key id of the log event server.String. The secret key of the log event server.String. The URL of the log event server.SuccessCallbackFailureCallbackEventCallbackMethod 2: Not recommended (Deprecated)
TrustVisionSdk.shared.initialize(
accessKeyId: "your_access_key",
accessKeySecret: "your_secret_key",
baseUrl: "baseUrl",
localizationFiles: nil,
clientSettingsJsonString: nil,
localizationFiles: nil,
languageCode: "vi",
theme: TVTheme(),
xRequestId: nil,
xRequestId2: nil,
isForced: false,
enableDebuggingLog: false,
tvCertificate: TVCertificate(name:"your_name_ssl_pining_certificate_file", type: "your_name_ssl_pining_certificate_type"),
imageEncryptionKey: "your_key",
securityPublicKey: "your_security_public_key"
success: {
// sdk is initialized
}, failure: { error in
// sdk is failed to initialize
}, onEvent: { event in
// sdk is initialized with event
}
)
Options:
String. The access key id of the server.String. The secret key of the server.String. The endpoint of the server.String. The jsonConfigurationByServer is optional but recommended.
It's the setting specialized for each client from TS server.
It's the response json string get by API https://ekyc.trustingsocial.com/api-reference/customer-api/#get-client-settings.
When it's null or unmatched with the expected type then the default setting in the SDK will be used.String. Language code. vi or enTVTheme. UI customization theme.TVCertificate?. init ssl pining certificateString?. For image encrypt. Set nil to ignore encryptionString?. For public key. Set nil to use it default in TSString (optional) https://ekyc.trustingsocial.com/api-reference/customer-api#api-reconciliationString (optional) another xRequestIdSuccessCallbackFailureCallbackEventCallbackAllow user to change the sdk language after initialization
TrustVisionSdk.shared.changeLanguageCode(languageCode: String)
TrustVisionSdk.shared.getLanguageCode() -> String?
TrustVisionSdk.shared.getSupportedLanguageCodes() -> []
The SDK provides some built in Activities example activity to capture id, selfie, liveness...
The id capturing activity will show the camera to capture image, preview the image. To start the id capturing activity.
let config = TVIdCardConfiguration(
cardTypes: [TVCardType],
cardSide: TVIdCardConfiguration.TVCardSide.front,
isSoundEnable: false,
isReadBothSide: false,
idTamperingLevel: nil,
skipConfirmScreen: false,
idCaptureOnlyMode: false,
isEnablePhotoGalleryPicker: false,
isEnableScanQr: true,
isEnableScanNfc: true,
isEnableVerifyNfc: true,
isSanityRequired: false,
isIdCardTamperingDetectionEnable: false,
isEnableReadCardInfo: false,
isEnableUploadFrames: true,
isEnableUploadImages: true,
isEnableCallApiOcrNfc: true
)
Options:
[TVCardType]. Card types are allowed to capture. List of supported cards can be found in this table:| card_type | description | supported countries |
|---|---|---|
TVCardType.defaultVnCardType() | Any of Vietnam national ID versions | vietnam |
TVCardType.cmnd() | Chứng minh nhân dân cũ | vietnam |
TVCardType.cmndNew() | Chứng minh nhân dân mới | vietnam |
TVCardType.cccd() | Căn cước công dân | vietnam |
TVCardType.cccdNew() | Căn cước công dân gắn chip | vietnam |
TVCardType.passport() | Vietnam passport | vietnam |
TVCardType.tcc() | Thẻ căn cước | vietnam |
TVCardSide. Card side to captureBool. Sound should be played or notBool. If true then the sdk will capture both side if possible; otherwise, then the card side defined in cardSide will be usedString?. Tampering level each side of id cardBool. Skip id capturing confirmation screen nor notBool. Just take front and back id card, no further processing sanity, tampering, read id card.Bool. Allow user select id card image from phone galleryBool. Allow user select scan QR code of the id card or notBool. Allow user select scan NFC chip of the id card or notBool. Enable verify NFC or not. If it's true then the SDK will call the API to verify the NFC data.Bool. Enable sanity check or not. If it's true then the SDK will call
the API to check the sanity of the id card.Bool. Enable ID Tampering Verification or not. If it's true then the SDK
will call the API to
check the tampering of the id card.Bool. Enable read card info or not. If it's true then the SDK will call
the API to read the card info.Bool. Enable upload video frames or not. If it's false then the SDK won't call the API to upload
the frames and the APIs that need the video frames will be skipped or called with empty frames data.Bool. Enable upload images or not. If it's false then the SDK won't call the API to upload
the images and the APIs that need the image will be skipped.Bool. Enable read card info or not. If it's true then the SDK will call
the API to read the card image id, then go to verify NFC.let vc = TrustVisionSdk.shared.startIdCapturing(configuration: config, framesRecordedCallback: { batchId, frames, metadata, currentBatchIds in
}, readIdCardNumber: { (image) in
return ""
}, success: { (result) in
}, failure: { (error) in
}, cancellation: { (cancellation) in
// sdk is canceled
})
where:
configuration: TVIdCardConfiguration
framesRecordedCallback:
String. new coming local batch idDictionary. batch frame to pushDictionary. batch metadata to push[String]. For debugging onlyThis callback will be called each time there is a new frame batch coming. Client upload and get the batch id which is used for later id tampering api call.
success: method that will be called in case success. Parameters:
TVDetectionResult. Use the following fields:TVImageClassTVImageClassTVCardQrTVCardQrTVNfcInfoResultfailure: FailureCallback
cancellation: CancellationCallback
readIdCardNumber: method that will be called in case of scan NFC to read SDK Id number from the image. The readIdCardNumber method has a parameter and return a string which is the id number of the card.
TVImageClass. image of back id cardWith each batch that returned by framesRecordedCallback callback,
call the below api to get server frame batch id, keep it corresponds to batchId returned in framesRecordedCallback - local id
https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
For example:
var frontCardFrameBatchIdsDictionary: [String: String] = [:]
var backCardFrameBatchIdsDictionary: [String: String] = [:]
. . .
framesRecordedCallback = { batchId, frames, metadata, currentBatchIds in
let batchDict = frames.merging(["metadata": metadata, "label": "The card type"]) { $1 }
let jsonToBeUploaded = try JSONSerialization.data(withJSONObject: batchDict, options: .prettyPrinted)
// upload frame batch to server using this api:
// https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
doYourUploadFrameBatchHere(withJSON: jsonToBeUploaded) { uploadingResult in
if cardSide == TVIdCardConfiguration.TVCardSide.front {
frontCardFrameBatchIdsDictionary.updateValue(uploadingResult.fileId, forKey: batchId)
}
else {
backCardFrameBatchIdsDictionary.updateValue(uploadingResult.fileId, forKey: batchId)
}
}
}
For example:
// These lists contain all valid frame batch ids that responded by server
var validFrontCardServerFrameBatchIds: [String] = []
var validBackCardServerFrameBatchIds: [String] = []
private func removeRedudantFrameBatchIds(batchIdsDictionary: [String: String], validIdsFromSDK: [String]) -> [String] {
return batchIdsDictionary.compactMap({
if validIdsFromSDK.contains($0.key) {
return $0.value
}
else {
return nil
}
})
}
. . .
success = { result in
// result.frontCardFrameBatchIds && result.backCardFrameBatchIds is empty when Frame Recording feature is disabled by client settings.
// Wait until every Frame batch has been uploaded to server before calling this
if(everyFrameBatchUploadingCompleted) {
if (!result.frontCardFrameBatchIds.isEmpty) {
validFrontCardServerFrameBatchIds = removeRedudantFrameBatchIds(frontCardFrameBatchIdsDictionary, result.frontCardFrameBatchIds)
}
if (!result.backCardFrameBatchIds.isEmpty) {
validBackCardServerFrameBatchIds = removeRedudantFrameBatchIds(backCardFrameBatchIdsDictionary, result.backCardFrameBatchIds)
}
}
}
Use this API https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image The images should be uploaded as JPEG data with 100% quality. For example:
// with front side
let dataToUpload = result.frontIdImage.imageByteArray
let frontCardId = yourMethodToUploadImage(dataToUpload)
// with back side
let dataToUpload = result.backIdImage.imageByteArray
let backCardId = yourMethodToUploadImage(dataToUpload)
if result.frontIdQr.isRequired is true then result.frontIdQr.images array should be non-empty. Otherwise, clients should be warned to re-capture id card photos.
QR images will be uploaded with this api: https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image
let dataToUpload = result.frontIdQr.images[i].imageByteArray
let qrId = yourMethodToUploadImage(dataToUpload)
dataToUploadresult.frontIdQr.images[i].labelresult.frontIdQr.images[i].metadata*The same logic will be applied to result.backIdQr
Call this API https://ekyc.trustingsocial.com/api-reference/customer-api/#request-detect-id-card-tampering with params:
{
"image": {
"id": "<frontCardId>"
},
"image2": {
"id": "<backCardId>"
},
"qr1_images": [{
"id": "<qrId>"
}],
"card_type": "<result.cardType.id>",
"videos": [{
"id": "<validFrontCardServerFrameBatchIds[index]>"
},
{
"id": "<validFrontCardServerFrameBatchIds[index + 1]>"
},
...
{
"id": "<validBackCardServerFrameBatchIds[index]>"
},
{
"id": "<validBackCardServerFrameBatchIds[index + 1]>"
},
...
]
}
After capture the back card, if the card has nfc chip, SDK will call readIdCardNumber method in background thread. With image that returned by readIdCardNumber,
call api to detect id number of the card then return id number to start flow scan NFC. If id number is null or empty, SDK skip flow scan NFC and continue
readIdCardNumber: { [weak self] (image) in
var idNumber = ""
// call api or do any thing to read and return id number
// TODO
return idNumber
}
The selfie capturing activity will show the camera to capture image, preview the image and verify active liveness in local. To start the selfie capturing activity.
let config = TVSelfieConfiguration(
cameraOption: TVCameraOption.front,
isSoundEnable: true,
skipConfirmScreen: true,
livenessMode: TVLivenessMode.flash_16,
isSanityRequired: true,
isEnableVerifyLiveness: true,
isEnableUploadFrames: true,
isEnableUploadImages: true,
isEnableExitConfirmPopup: false)
Options:
TVCameraOption. Set the camera modeBool. Sound should be played or notBool. Skip selfie capturing confirmation screen or notTVLivenessMode. Set the liveness verification modeBool. Enable sanity check or not. If it's true then the SDK will call
the API to check the sanity of the selfie.Bool. Enable liveness verification or not. If it's true
then the SDK will call the API to verify the liveness of the selfie.Bool. Enable upload video frames or not. If it's false then
the SDK won't call the API to upload the frames and the APIs that need the video frames will be skipped or called with empty frames data.Bool. Enable upload images or not. If it's false then
the SDK won't call the API to upload the images and the APIs that need the image will be skipped.Bool. Enable exit confirm popup or not. If it's true then the SDK will show the exit confirm popup when the user tries to exit the selfie capturing activity.let vc = TrustVisionSdk.shared.startSelfieCapturing(configuration: config,
framesRecordedCallback: { batchId, frames, metadata, currentBatchIds in
}, success: { (result) in
}, failure: { (error) in
}, cancellation: { (cancellation) in
// sdk is canceled
})
where:
configuration: TVSelfieConfiguration
framesRecordedCallback:
String. new coming local batch idDictionary. batch frame to pushDictionary. batch metadata to push[String]. For debugging onlyThis callback will be called each time there is a new frame batch coming. Client upload and get the batch id which is used for later selfie liveness api call.
success method that will be called in case success. Parameters:
TVDetectionResult . Use the following fields:[TVGestureImage]. List images includes frontal and gesture faces.[String]. List valid frame batch id in liveness.[TVImageClass]. List images includes frontal faces.[TVGestureFace]. List images includes gesture faces.failure: FailureCallback
cancellation: CancellationCallback
With each batch that returned by framesRecordedCallback callback,
call the below api to get server frame batch id, keep it corresponds to batchId returned in framesRecordedCallback - local id
https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
For example:
// this dictionary will be used for Liveness verification
var selfieFrameBatchIdsDictionary: [String: String] = [:]
. . .
framesRecordedCallback = { batchId, frames, metadata, currentBatchIds in
let batchDict = frames.merging(["metadata": metadata, "label": "video"]) { $1 }
let jsonToBeUploaded = try JSONSerialization.data(withJSONObject: batchDict, options: .prettyPrinted)
// upload frame batch to server using this api:
// https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
doYourUploadFrameBatchHere(withJSON: jsonToBeUploaded) { uploadingResult in
// Keep the id that generated by the SDK corresponding with the one responded from server
selfieFrameBatchIdsDictionary.updateValue(uploadingResult.fileId, forKey: batchId)
}
}
For example:
// These lists contain all valid frame batch ids that responded by server
var validServerFrameBatchIds: [String] = []
private func removeRedudantFrameBatchIds(batchIdsDictionary: [String: String], validIdsFromSDK: [String]) -> [String] {
return batchIdsDictionary.compactMap({
if validIdsFromSDK.contains($0.key) {
return $0.value
}
else {
return nil
}
})
}
. . .
success = { result in
// result.livenessFrameBatchIds is empty when Frame Recording feature is disabled by client settings.
// Wait until every Frame batch has been uploaded to server before calling this
if(everyFrameBatchUploadingCompleted) {
if (!result.livenessFrameBatchIds.isEmpty) {
validServerFrameBatchIds = removeRedudantFrameBatchIds(selfieFrameBatchIdsDictionary, result.livenessFrameBatchIds)
}
}
}
https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-image The images should be uploaded as JPEG data with 100% quality. For example:
// with frontal images
let dataToUpload = result.selfieImages[i].frontalImage.imageByteArray
// with gesture images
let dataToUpload = result.selfieImages[i].gestureImage.imageByteArray
id of frontal image i = image id of result.selfieImages[i].frontalImage.imageByteArray
id of gesture image i = image id of result.selfieImages[i].gestureImage.imageByteArray
https://ekyc.trustingsocial.com/api-reference/customer-api/#upload-videoaudioframes
id of selfie video i = video id of result.livenessVideos[i]
API document: https://ekyc.trustingsocial.com/api-reference/customer-api/#verify-face-liveness
Call the above api with below parameters:
images field{
"images": [
{
"id": "<result.selfieImages[index].frontalImage.imageId>"
},
{
"id": "<result.selfieImages[index + 1].frontalImage.imageId>"
},
...
]
}
gesture_images field{
"gesture_images": [
{
"gesture": "<result.selfieImages[index].gestureType.description>",
"images": [{
"id": "<result.selfieImages[index].gestureImage.imageId>"
}]
},
{
"gesture": "<result.selfieImages[index + 1].gestureType.description>",
"images": [{
"id": "<result.selfieImages[index + 1].gestureImage.imageId>"
}]
},
...
]
}
videos field{
"videos": [
{
"id": "<validServerFrameBatchIds[index]>"
},
{
"id": "<validServerFrameBatchIds[index + 1]>"
},
...
]
}
metadata field{
"metadata": "<result.livenessMetadata>"
}
The QR scanning activity will show the camera to scan image, preview the image. To start the QR scanning activity.
let config = TVQRConfiguration(
cardTypes: [TVCardType],
cardSide: TVIdCardConfiguration.TVCardSide.front,
skipConfirmScreen: true,
isEnableUploadFrames: false,
isEnableUploadImages: false
)
Options:
[TVCardType]. Card types are allowed to capture. List of supported cards can be found in this table:| card_type | description | supported countries |
|---|---|---|
TVCardType.defaultVnCardType() | Any of Vietnam national ID versions | vietnam |
TVCardType.cmnd() | Chứng minh nhân dân cũ | vietnam |
TVCardType.cmndNew() | Chứng minh nhân dân mới | vietnam |
TVCardType.cccd() | Căn cước công dân | vietnam |
TVCardType.cccdNew() | Căn cước công dân gắn chip | vietnam |
TVCardType.passport() | Vietnam passport | vietnam |
TVCardSide. Card side to captureBool. Skip id capturing confirmation screen nor notBool. Enable upload video frames or not. If it's false then
the SDK won't call the API to upload the frames and the APIs that need the video frames will be skipped or called with empty frames data.Bool. Enable upload images or not. If it's false then
the SDK won't call the API to upload the images and the APIs that need the image will be skipped.let vc = TrustVisionSdk.shared.startQRScanning(configuration: config, success: { (result) in
}, failure: { (error) in
}, cancellation: { (cancellation) in
// sdk is canceled
})
where:
TVQRConfigurationTVDetectionResult. Use the following fields:FailureCallbackCancellationCallbackThe NFC scanner activity will show the guideline screen, the scanner popup. To start the NFC scanner activity.

<key>NFCReaderUsageDescription</key>
<string>This app would like to use NFC to scan CCCD chip</string>
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
<string>A0000002471001</string>
<string>A0000002472001</string>
<string>00000000000000</string>
</array>
let config = TVIdNfcConfiguration(
nfcCode: nfcCode,
nfcSod: sod,
cardIssueDate: issueDate,
nfcCacheFields: nfcCacheFields,
isRequestReadImageNfc: true,
isRequestCloneDetectionNfc: true,
isRequestIntegrityCheckNfc: true,
nfcMaxRetries: 5,
isEnableCheckNfcData: true,
isEnableVerifyNfc: true,
dateOfBirth: "dd/MM/yyyy",
dateOfExpiry : "dd/MM/yyyy"
)
Options:
String is the id number of ID cardString (optional) is the hash of SOD, hash_sod get from API https://ekyc.trustingsocial.com/api-reference/customer-api#2-response-38String (optional) is the issue date of ID card (DD/MM/YYYY)List<String> (optional) is the list of fields that was cached from previous scanning, input_fields from from API https://ekyc.trustingsocial.com/api-reference/customer-api#2-response-38Bool. Read image in the chip when scan nfc or notBool. Check clone of the chip when scanning nfc or notBool. Check integrity of the chip when scanning nfc or notInt. The maximum number of times the SDK retries an NFC scanning before giving upBool. Enable check NFC data or not. If it's true then the SDK will call
the API to get sod and cached fields of the NFC data.Bool. Enable verify NFC or not. If it's true then the SDK will call
the API to verify the NFC data.String? (optional) is the date of birth (dd/MM/yyyy)String? (optional) is the expired of ID card (dd/MM/yyyy). For cards with unlimited expiration, please input: 31/12/9999let vc = TrustVisionSdk.shared.startNfcScanning(configuration: config, success: { (result) in
}, failure: { (error) in
}, cancellation: { (cancellation) in
// sdk is canceled
})
where:
TVQRConfigurationTVDetectionResult. Use the following fields:TVNfcInfoResultFailureCallbackCancellationCallbackThe face authentication activity will show the camera to capture the face, preview the image.
let authenConfigurationComponents = TVAuthenConfigurationComponents(
selfieConfig: selfieConfig,
cardConfig: cardConfig,
nfcConfig: nfcConfig)
let config = TVFaceAuthenConfiguration(
type: TVFaceAuthenType.register,
userId: "user_id",
method: TVFaceAuthenMethod.active,
authenConfigurationComponents: authenConfigurationComponents,
isEnableFaceAuthentication: true,
isEnableFaceRegistration: true
)
Options:
TVFaceAuthenType. Set the TVFaceAuthenType mode to register or authenticate.String is the user idTVFaceAuthenMethod. Set the TVFaceAuthenMethod mode to authen.TVAuthenConfigurationComponents. Set up the configurations. Use the following fields:TVSelfieConfiguration (optional): set it if you want to use selfie capturing in face authentication.TVIdCardConfiguration (optional): set it if you want to use scan nfc in face authentication.TVIdNfcConfiguration (optional): set it if you want to use scan nfc in face authentication.Bool. Enable call API face authentication or notBool. Enable call API face registration or notlet vc = try TrustVisionSdk.shared.startFaceAuthen(
config: config,
framesRecordedCallback: { batchId, frames, metadata, currentBatchIds in
},
onLoading: {
},
success: { [weak self] (result) in
},
failure: { (error) in
}, cancellation: { (cancellation) in
// sdk is canceled
})
where:
config: TVFaceAuthenConfiguration
framesRecordedCallback:
String. new coming local batch idDictionary. batch frame to pushDictionary. batch metadata to push[String]. For debugging onlyThis callback will be called each time there is a new frame batch coming.
onLoading: the callback provides the loading screen at the host app when the SDK is processing for request face authentication.
success: method that will be called in case success for register. Parameters:
TVDetectionResult. Use the following fields:TVFaceAuthRegisterResult.TVFaceAuthResult.failure: FailureCallback
cancellation: CancellationCallback
Note: Sample code for face authentication in the case of initializing the SDK with the parameters endpoint, accessKeyId, and accessKeySecret.
// Define configs as you need. Example:
let selfieConfig = TVSelfieConfiguration(
cameraOption: .front,
isSoundEnable: true,
skipConfirmScreen: true,
livenessMode: .active,
isSanityRequired: false,
isEnableVerifyLiveness: false,
isEnableUploadFrames: false,
isEnableUploadImages: false
)
let cardConfig = TVIdCardConfiguration(
cardTypes: [TVCardType.id],
cardSide: .front,
isSoundEnable: true,
isReadBothSide: false,
idTamperingLevel: nil,
skipConfirmScreen: false,
idCaptureOnlyMode: false,
isEnablePhotoGalleryPicker: false,
isEnableScanQr: true,
isEnableScanNfc: true,
isEnableVerifyNfc: true,
isSanityRequired: false,
isIdCardTamperingDetectionEnable: false,
isEnableReadCardInfo: false,
isEnableUploadFrames: true,
isEnableUploadImages: true
)
let nfcConfig = TVIdConfirmationTheme(
nfcCode: "nfc_code",
nfcSod: "nfc_sod",
cardIssueDate: "card_issue_date",
nfcCacheFields: ["nfc_cache_field"],
isRequestReadImageNfc: true,
isRequestCloneDetectionNfc: true,
isRequestIntegrityCheckNfc: true,
nfcMaxRetries: 5,
isEnableCheckNfcData: true,
isEnableVerifyNfc: true
)
// Set up config for face authentication
let authenConfigurationComponents = TVAuthenConfigurationComponents(
selfieConfig: selfieConfig,
cardConfig: cardConfig,
nfcConfig: nfcConfig)
let config = TVFaceAuthenConfiguration(
type: .register,
userId: cusUserId,
method: TVFaceAuthSession.shared.registerFaceMethod,
authenConfigurationComponents: authenConfigurationComponents,
isEnableFaceAuthentication: false,
isEnableFaceRegistration: false
)
// Start face authentication
TrustVisionSdk.shared.startFaceAuthen(
config: config,
framesRecordedCallback: { batchId, frames, metadata, currentBatchIds in
// Handle frame recorded callback
},
onLoading: {
// Handle loading screen at your side when the SDK is processing for request face authentication
// Leave it if you do need it, do not forget to stop loading after the SDK returns success, failed, or canceled
},
success: { [weak self] (result) in
// Handle success
self?.handleSuccessFaceAuthen(result)
},
failure: { (error) in
// Handle failure
},
cancellation: { (cancellation) in
// Handle cancellation
}
func handleSuccessFaceAuthen(_ result: TVDetectionResult) {
var selfieImages = result.selfieImages
let videos: [TVRequestVideo] = result.livenessFrameBatchIds.map{TVRequestVideo(id: $0)}
var faces : [TVRequestImage] = result.faces.map{TVRequestImage(id: $0.imageId)}
var gestures : [TVGestureFace] = result.gestureFaces.map{TVGestureFace(gesture: $0.gestureType.description.lowercased(), images: [TVRequestImage(id: $0.gestureImage.imageId)])
// call api to verify face authentication
// https://ekyc.trustingsocial.com/api-reference/customer-api#request-face-authentication
let faceAuthenRequest = TVRequestFaceAuthen(
cusUserId
images: faces,
gestureImages: gestures,
videos: videos,
"selfie",
"transfer"
)
yourMethodToCallFaceAuthenticationAPI(request)
}
// [FlowStartingFunc]: startIdCapturing, startSelfieCapturing, startQRScanning, startNfcScanning, startFaceAuthen
TrustVisionSdk.shared.[FlowStartingFunc]
(config: ...,
error: { [weak self] error in
// Handle error
self?.handleError(error)
})
func handleError(_ error: TVError) {
switch error.category {
case .local:
// Handle SDK error
switch error.errorCode {
case "unidentified":
// unidentified error (general)
case "authentication_missing_error":
// sdk is not initialized
case "sdk_canceled":
// sdk is canceled by user
case "permission_missing_error":
// permission missing error (example: camera permission)
case "setupSDK":
// fail to set up sdk
case "max_retry_reached":
// When the SDK reaches the maximum timeout, this only applies to FlashLiveness
default:
// Handle other local errors
}
case .server:
// Handle server error
// The SDK has an unexpected error when calling API
// https://ekyc.trustingsocial.com/api-reference/customer-api#response-errors
}
}
The SDK provides some built-in API for quick detection
Allow users to quick check if device support NFC so that they can determine for their next step
TrustVisionSdk.shared.isNfcSupport() -> Bool
Allow users to get device information: TVDeviceInfoProvider
let deviceInfo = TrustVisionSdk.shared.getDeviceInfo()
TVDeviceInfoProvider contains following properties (will return nil if SDK cannot get information of that property)
| Property | Type | Description |
|---|---|---|
id | String | Device Id |
udid | String | Same as above, Unique Device Id |
sn | String | Serial Number |
imei | String | IMEI |
manufacturer | String | Manufacturer |
deviceName | String | Device name |
wlanMac | String | Wireless mac address |
phoneNumber | String | Current Phone Number |
location | LocationInfo | Location information {longitude, latitude} |
LocationInfo contains following properties (will return empty string if SDK cannot get information of that property)
Please request location permission from your app first.
| Property | Type |
|---|---|
longitude | String |
latitude | String |
| Properties | Type | description |
|---|---|---|
frontIdImage | TVImageClass | Image of id card's front side (use field imageByteArray) |
backIdImage | TVImageClass | Image of id card's back side (use field imageByteArray) |
frontIdQr | TVCardQr | Info of QR of id card's front side |
backIdQr | TVCardQr | Info of QR of id card's back side |
frontCardFrameBatchIds | [String] | List of front id frame batch IDs |
backCardFrameBatchIds | [String] | List of back id frame batch IDs |
nfcInfoResult | TVNfcInfoResult | Info in nfc chip. Use it to call api verify NFC |
| Properties | Type | description |
|---|---|---|
livenessResult | TVLivenessResult | Liveness check result |
selfieImages | [TVGestureImage] | Images of selfie |
livenessFrameBatchIds | [String] | List of selfie frame batch IDs |
livenessVideos | [Data] | List of video data during checking liveness |
livenessMetadata | [String: Any]? | Collected data during liveness checking process |
Will be called in case failed. Parameters:
TVError.Will be called in case the sdk is cancelled. No parameters
| Properties | Type | Description |
|---|---|---|
com | String | |
sod | String | |
dg1 | String | |
dg2 | String | |
dg13 | String | |
dg14 | String | |
dg15 | String | |
getCloneStatus() | TVNfcVerificationResultStatus |
| Properties | Type | Description |
|---|---|---|
error | TVError | |
verdict | TVNfcVerdict | TVNfcVerdict.notChecked TVNfcVerdict.alert TVNfcVerdict.good TVNfcVerdict.error |
| Properties | Type | Description |
|---|---|---|
requestId | String | |
status | String | success, failure |
| Properties | Type | Description |
|---|---|---|
requestId | String | |
status | String | success, failure |
matchResult | TVCompareFacesResult.MatchResult.matched | TVCompareFacesResult.MatchResult.matched TVCompareFacesResult.MatchResult.unmatched TVCompareFacesResult.MatchResult.unsure |
score | Float |