tencent cloud

Integration of IOS Client SDK
Last updated: 2025-12-02 17:25:44
Integration of IOS Client SDK
Last updated: 2025-12-02 17:25:44

Service Process Diagram



Privacy Settings

Privacy Policy Link: Privacy Policy | Captcha.

Before adapting, integrating, or loading this SDK product into your product, application, or service, you should carefully read and agree to the related service agreement, these rules, and/or the third-party developer compliance guide (or similar legal documents) that we have published, and conduct a compliance self-check on the collection and use of personal information by the product that adapts, integrates, or loads this SDK product.
If you do not agree with any part of the privacy agreement, you should immediately stop accessing and using the SDK and/or related services. You should use this SDK product and process end users' personal information only after obtaining their consent. Before obtaining end users' consent, you should not enable or initialize this SDK.

iOS SDK Integration

 Integrate the SDK into your project.
Drag the TencentCaptcha directory from the SDK package into your project.
In Xcode, click your project and target, then open the "Build Settings" tab.
Locate "Library Search Paths", expand it, and add the Captcha directory if it is not automatically added.
Locate "Header Search Paths", expand it, and add the Captcha directory if it is not automatically added.
Ensure TencentCaptcha.a is linked with your project (Link Binary with Libraries).
Configuration Parameters
// Set the Captcha App ID before any logic that calls Tencent Captcha service
TencentCaptcha.setup { config in
// Replace __YOUR_CAPTCHA_APP_ID__ with your Captcha App ID
config.appID = __YOUR_CAPTCHA_APP_ID__
}
Configuration Parameter
// Please set the Captcha App ID before any call to the Tencent Captcha service
TencentCaptcha.setup { config in
// Please use your Captcha App ID to replace __YOUR_CAPTCHA_APP_ID__
config.appID = __YOUR_CAPTCHA_APP_ID__
}
Additional parameters can be configured based on your usage scenario, though most parameters work smoothly without modification in the SDK.
appID
Description
appID
Please use the AppID we assigned to you and enter it into this parameter.
tarsServerURL
Tars server address
captchaPageHost
Set the Host for the Captcha page
usesCacheToken
Whether using a cached token is allowed to speed up the request process
miniTuringShieldChannel
Channel number for risk identification business, fill in the channel ID we assigned to you
timeoutForNativeRequest
Request timeout duration for local device risk detection, in seconds
timeoutForNativePacking
Request timeout duration for local device risk detection, in seconds
timeoutForWebViewLoading
Deprecated. Please use 'timeout' uniformly. The timeout duration for page loading, in seconds.
timeout
Unified timeout settings API, in seconds
For more parameters, see the definition of TencentCaptchaConfiguration.
Set up WebView
The instance of WKWebView needs to be initialized by you. Due to some system limitations, the SDK cannot currently receive WKWebView generated from StoryBoard.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let contentController = WKUserContentController()
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: self.view.bounds, configuration: config)
webView.navigationDelegate = self
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(webView)
}
Guide users to agree to privacy policy
Important: Do not use this SDK until the user agrees to the privacy policy. Please configure the SDK as follows after the user agrees to the privacy policy:
TencentCaptcha.userDidAcceptPrivacyPolicy = true
Obtain Captcha characters
let options = TencentCaptchaOptions()
options.optionsCallback = { functionName, data in }
// TODO: Set other options as needed
TencentCaptcha.shared().requestCaptcha(withWebView: self.webView, options:options) { error, result in
if let error = error {
// If an error occurs, error is non-null
}
else {
// result is the return value
}
}

Set Parameters for the Captcha Interface

The `options` parameter passed when calling `TencentCaptcha.requestCaptcha()` can be configured to some additional parameters. Please refer to the definition of `TencentCaptchaOptions` for details.
Additional parameters can also be configured using `TencentCaptchaOptions.setExtractParameter()`. For example:
let options = TencentCaptchaOptions()
options.loadingEnabled = TencentCaptchaOptionsSwitchOn
options.setExtractParameter(true, forName: "enableAutoCheck")

TencentCaptcha.shared().requestCaptcha(withWebView: self.webView, options:options) { error, result in
// ...
}


Available Additional Paramete

Configuration Name
Value Type
Description
enableAutoCheck
Bool
When enabled, secure requests can automatically perform verify selection with no action required by the user.
true: Enabled.
false: Disabled.
nil: Default (disabled)

Class Declaration

TencentCaptchaOptions

Captcha Request Parameters
See `-requestCaptchaWithWebView:options:withCompletionHandler:`TencentCaptcha
/// Night mode option
typedef enum : NSUInteger {
/// Default
TencentCaptchaOptionsDarkModeDefault,
/// Turn on with the system
TencentCaptchaOptionsDarkModeTrue,
/// Always off
TencentCaptchaOptionsDarkModeFalse,
/// Force open
TencentCaptchaOptionsDarkModeForce,
} TencentCaptchaOptionsDarkMode;

typedef enum : NSUInteger {
TencentCaptchaOptionsSwitchDefault,
TencentCaptchaOptionsSwitchOn,
TencentCaptchaOptionsSwitchOff,
} TencentCaptchaOptionsSwitch;

/// Captcha Request Parameters
@interface TencentCaptchaOptions : NSObject

/// Custom pass-through parameters. The business can use this field to transmit a small amount of data. The content of this field will be entered into the object of the callback.
@property (nonatomic, strong, nullable) NSString *bizState;

/// Night mode
@property (nonatomic, assign) TencentCaptchaOptionsDarkMode darkModeEnabled;

/// Help button switch
@property (nonatomic, assign) TencentCaptchaOptionsSwitch needsFeedback;

/// Custom URLs of the help button
/// @discussion If `customFeedbackURL` is not empty, the `needsFeedback` option is unavailable, the help button is always displayed, and it navigates to this URL when clicked.
@property (nonatomic, strong, nullable) NSString *customFeedbackURL;

/// Specify the language of the Captcha prompt copy. The priority is higher than the console configuration.
@property (nonatomic, strong, nullable) NSString *userLanguage;

/// Aging adaptation mode
@property (nonatomic, assign) TencentCaptchaOptionsSwitch agedEnabled;

/// Define the display method of the Captcha
/// @discussion popup (default): Display the Captcha in a centered popup floating layer form.
@property (nonatomic, strong, nullable) NSString *type;

/// Whether to show a loading box during the Captcha loading process
@property (nonatomic, assign) TencentCaptchaOptionsSwitch loadingEnabled;

/// CaptchaAppId encrypted validation string
/// @discussion See https://www.tencentcloud.com/zh/document/product/1159/49680?lang=zh&pg=#captchaAppid
@property (nonatomic, copy, nullable) NSString *encryptedAppID;


/// Set additional parameters
/// @param value Parameter value
/// @param name Keyword name of the parameter
/// @discussion When the parameter corresponding to name does not exist, a new value will be inserted. If it exists, the new value will overwrite the old one; when value is nil, this parameter will be deleted.
- (void)setExtractParameter:(nullable id)value forName:(nonnull NSString *)name;

/// Additional parameters currently set
@property (nonatomic, strong, readonly, nonnull) NSDictionary<NSString *, id> *extractParameters;

@end

TencentCaptchaOptionsDarkMode
Night mode options
/// Night mode options
typedef enum : NSUInteger {
/// Default
TencentCaptchaOptionsDarkModeDefault,
/// Enabled with system
TencentCaptchaOptionsDarkModeTrue,
/// Always disabled
TencentCaptchaOptionsDarkModeFalse,
/// Force enabled
TencentCaptchaOptionsDarkModeForce,
} TencentCaptchaOptionsDarkMode;
TencentCaptchaOptionsSwitch
Switch Option
/// Switch Option
typedef enum : NSUInteger {
TencentCaptchaOptionsSwitchDefault,
TencentCaptchaOptionsSwitchOn,
TencentCaptchaOptionsSwitchOff,
} TencentCaptchaOptionsSwitch;

TencentCaptchaConfiguration

Captcha Service Configuration
See: `+setupWithConfigurationHandler:`TencentCaptcha
/// Captcha Service Configuration
/// - Use in `+[TencentCaptcha setupWithConfigurationHandler:]` to configure the service
/// - SeeAlso:
/// - Objective C: `+[TencentCaptcha setupWithConfigurationHandler:]`,
/// - Swift: `TencentCaptcha.setup(configurationHandler:)`
@interface TencentCaptchaConfiguration : NSObject
- (nonnull instancetype)init NS_UNAVAILABLE;
@property (nonnull, nonatomic, copy) NSString *appID;
/// Tars server address
/// - Note: If the purpose is unclear, do not set
@property (nullable, nonatomic, copy) NSURL *tarsServerURL;
/// Set the Host for the Captcha page
/// - Note:
/// - can only set the host part in the URL, such as the host part in `https://host/path/to/html`, other parts currently do not support modification
/// - If the host is invalid and causes the correct page URL to be unable to generate, the setting is invalid
/// - Set to nil to keep the default value
/// - If the purpose is unclear, do not set
@property (nullable, nonatomic, copy) NSString *captchaPageHost;
/// Whether using a cached token is allowed to speed up the request process
/// - Note: Defaults to YES. The cache policy meets needs in most scenarios. If you need special attention to real-time risk, set to NO.
@property (nonatomic, assign) BOOL usesCacheToken;

/// [Disabled, unified usage timeout]
/// Request timeout duration for local device risk detection, in seconds
@property (nonatomic, assign) NSTimeInterval timeoutForNativeRequest__attribute__((deprecated("NOT WORK! Use 'timeout' instead.")));

/// [Disabled, unified usage timeout]
/// Collection timeout duration for local device risk detection, in seconds
@property (nonatomic, assign) NSTimeInterval timeoutForNativePacking__attribute__((deprecated("NOT WORK! Use 'timeout' instead.")));

/// [Disabled, unified usage timeout]
/// Page loading timeout duration, in seconds
@property (nonatomic, assign) NSTimeInterval timeoutForWebViewLoading__attribute__((deprecated("NOT WORK! Use 'timeout' instead.")));

/// Unify timeout settings, in seconds. Internal stages perform timeout control allocation to simplify setting logic.
@property (nonatomic, assign) NSTimeInterval timeout;
@end


TencentCaptcha

/// The implementation class of the Captcha service
@interface TencentCaptcha : NSObject
- (nonnull instancetype)init NS_UNAVAILABLE;
/// The singleton of the Captcha service
+ (nonnull instancetype)sharedService NS_SWIFT_NAME(shared());
/// Configuration service options
/// - Parameter configurationHandler: To modify the configuration, change the properties in the configuration provided in this callback function
- (void)setupWithConfigurationHandler:(nonnull void(^)(TencentCaptchaConfiguration *_Nonnull))configurationHandler NS_SWIFT_NAME(setup(configurationHandler:));
/// Request Captcha
/// - Parameters:
/// - webView: The web view used to display the Captcha
/// - options: Captcha request parameters
/// - completionHandler: Completion callback for verification
///
/// @discussion Due to some system limitations, the SDK cannot currently receive WKWebView generated from StoryBoard.
- (void)requestCaptchaWithWebView:(nonnull WKWebView *)webView options:(nullable TencentCaptchaOptions *)options withCompletionHandler:(nonnull void(^)(NSError *_Nullable error, NSDictionary *_Nullable result))completionHandler NS_SWIFT_NAME(requestCaptcha(withWebView:options:withCompletionHandler:));

/// Set additional parameters
/// @param value Parameter value
/// @param name Keyword name of the parameter
/// @discussion When the parameter corresponding to name does not exist, a new value will be inserted. If it exists, the new value will overwrite the old one; when value is nil, this parameter will be deleted.
- (void)setExtractParameter:(nullable id)value forName:(nonnull NSString *)name;

/// Additional parameters currently set
@property (nonatomic, strong, readonly, nonnull) NSDictionary<NSString *, id> *extractParameters;

@end
TencentCaptcha
The implementation class of the verification code service, used to provide Captcha service. It works in singleton method.
/// Captcha service implementation class
/// - Provides main Captcha service capacity
/// - Example:
/// ```swift
/// // Step 1. Guide user to agree to the User Privacy Agreement, then set `userDidAcceptPrivacyPolicy`
/// TencentCaptcha.userDidAcceptPrivacyPolicy = true
/// // Step 2. Initialize SDK
/// TencentCaptcha.setup(...)
/// // Step 3. Generate WebView and configure
/// webView = WKWebView(...)
/// self.view.addSubview(webView)
/// // Step 4. Generate and display Captcha
/// TencentCaptcha.requestCaptcha(...)
///
@interface TencentCaptcha : NSObject
- (nonnull instancetype)init NS_UNAVAILABLE;
/// Captcha service singleton
+ (nonnull instancetype)sharedService NS_SWIFT_NAME(shared());
/// Whether the user has approved the privacy policy
/// Before calling any SDK feature, please first guide the user to agree to the privacy policy, then set this property to `YES` / `true`
/// - Example:
/// ```swift
/// // User agreed to the privacy policy
/// TencentCaptcha.userDidAcceptPrivacyPolicy = true
/// ```
/// - Warning: The SDK does not provide Captcha service before the user agrees to the privacy policy
@property (nonatomic, assign, class) BOOL userDidAcceptPrivacyPolicy;
@property (nonatomic, readonly, nonnull, class) TencentCaptchaConfiguration *configuration;
/// Configuration service options
/// - Parameters:
/// - configurationHandler: if needed, modify the attributes of the configuration provided in this callback function
///
/// - Example: Minimize settings
/// ```
/// TencentCaptcha.setup { config in
/// config.appID = __YOUR_CAPTCHA_APP_ID__ // Please use your Captcha App ID to replace __YOUR_CAPTCHA_APP_ID__
/// }
/// ```
/// - Note: Please configure the service as early as possible and ensure setup before use
/// - SeeAlso: `TencentCaptchaConfiguration`
+ (void)setupWithConfigurationHandler:(nonnull void(^)(TencentCaptchaConfiguration *_Nonnull))configurationHandler NS_SWIFT_NAME(setup(configurationHandler:));
/// Request a Captcha
/// - Parameters:
/// - webView: web view for showing Captcha, needs to be initialized by caller
/// - options: Captcha request parameters
/// - completionHandler: callback for verification completion
///
/// - Example:
/// ```swift
/// TencentCaptcha.shared().requestCaptcha(withWebView: webView, options: options) { error, result in
/// if let result = result {
/// // When token is not empty, Captcha verification succeeds
/// }
/// else {
/// // Otherwise error will output error, see the document for specific error domain and error code
/// }
/// }
/// ```
///
/// - Warning: Due to certain system limitations, the SDK is temporarily unable to receive WKWebView generated from StoryBoard. Please use code to initialize a WKWebView and pass it to the SDK, for example:
/// ```swfit
/// let contentController = WKUserContentController()
/// let config = WKWebViewConfiguration()
/// config.userContentController = contentController
/// webView = WKWebView(frame: self.view.bounds, configuration: config)
/// webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
/// self.view.addSubview(webView)
/// ```
- (void)requestCaptchaWithWebView:(nonnull WKWebView *)webView options:(nullable TencentCaptchaOptions *)options withCompletionHandler:(nonnull void(^)(NSError *_Nullable error, NSDictionary *_Nullable result))completionHandler NS_SWIFT_NAME(requestCaptcha(withWebView:options:withCompletionHandler:));

Field Description

Field description of error in the completion callback (completionHandler).
When an error occurs, error is non-null and result is null. See Common mistakes.
Field description of result in the completion callback (completionHandler).
When the Captcha completes normally, error is null and result is non-null. Note that user verification failure is considered a normal completion of the Captcha.
Field Name
Value Type
Description
ret
Int
Verification result, 0: Verification successful. 2: User actively closes the Captcha.
ticket
String
Ticket returned by the Captcha, ticket has a value if and only if ret = 0.
CaptchaAppId
String
Captcha Application ID.
bizState
Any
Custom pass-through parameters.
randstr
String
The random string for this verification, which needs to be passed during subsequent ticket verification.
errorCode
Number
Error code. For details, see Callback function errorCode description.
errorMessage
String
Error message.

Common mistakes

Device Safety Layer Error (Error Domain TSLocalErrorDomain)

Error Code
Description
0
No error
1
Request protocol packaging error
2
Reply protocol unpacking error
3
Empty reply error
31
X1 protocol data compression error
4
Shark protocol shark layer unpacking error
5
Shark protocol shark layer does not contain sashimi
6
Shark protocol sashimi layer unpacking error
7
Shark protocol sashimi layer empty packet error
8
Shark protocol registration GUID error
9
Shark protocol save GUID error
10
Shark protocol unrecognized command word
20
Session expiration
21
Abnormal return of Shark Skin layer
22
Shark Skin layer unpacking error
23
Shark protocol sashimi layer return value is non-zero
11
The record is empty
12
The record content is invalid or some data is missing (error details available in DEBUG mode)
13
GUID not included when sending Shark request (currently only theoretically possible)
14
Record not included when sending Shark/WUP request
15
Current GUID does not correctly correspond to server type
16
Neither error nor server response included when generating reply content (currently only theoretically possible)
17
Client error for HTTP request (status code between 400~499)
18
Server error for HTTP request (status code between 500~599)
19
Received response does not correspond to the request
25
Temporarily unable to request
26
Illegal internal call
27
Request timeout
28
Illegal communication protocol, or incorrect communication protocol selected
29
Request queue too long
30
User/business side cancels the request
24
Internal testing reserved
34
Serialization failure when generating a token.
35
User has not agreed to the privacy policy.
38
Channel number not correctly set
37
unavailable method or function
36
Exception capture (detailed anomalies will be provided in error.userInfo)


 

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback