This topic describes how to integrate the Alibaba Cloud Device Risk SDK for iOS.
Prerequisites
iOS 9.0 or later.
Permissions
To improve risk detection accuracy, add the following fields and descriptions to your app's Info.plist before publishing to the App Store. Otherwise, your app may fail App Store review.
Permission | Required | Description |
NSLocalNetworkUsageDescription | No (recommended) | Obtains device connectivity within the local network to detect risks such as device farms and group control. |
NSLocationWhenInUseUsageDescription | No (recommended) | Obtains device location information to detect risks such as fake location spoofing. |
NSUserTrackingUsageDescription | No (recommended) | Used to obtain IDFA information, which helps improve device fingerprint stability. |
Configure dependencies
Download the iOS SDK (a standard static framework for Xcode) and generate an AppKey in the download console.
NoteThe single-architecture framework file is approximately 2.5 MB.
To ensure anti-reverse engineering capabilities and data security during network transmission, the SDK includes extensive interleaving, padding, and encryption operations, resulting in a larger file size.
Copy
deviceiOS.frameworkfrom the SDK package to your iOS project directory.In project settings, navigate to Build Phases -> Link Binary With Libraries, and add
deviceiOS.frameworkalong with its dependencies:deviceiOS.framework CoreTelephony.framework CoreLocation.framework Security.framework libresolv.tbd libz.tbd libc++.tbd // Add the following for the IDFA version AppTrackingTransparency.framework AdSupport.frameworkBased on your business requirements, choose whether to use an SDK version that collects sensitive data such as
idfa. For details, see the SDK download list.
Call the SDK
Initialize data collection
Initialize the SDK and start collecting data as early as possible in your risk scenarios, after the user has agreed to the privacy policy.
Function prototype
@interface SecurityDevice : NSObject
/**
* Initialize the device fingerprint SDK.
*/
- (void)initDevice:(NSString *)userAppKey :(void (^)(int))initCallback;
/**
* Initialize the SDK with options.
*/
- (void)initDevice:(NSString *)userAppKey withOptions:(NSMutableDictionary *)options callback:(void (^)(int))initCallback;
@endParameters
userAppKey: Identifies the user. This is the product AppKey assigned by Alibaba Cloud (different from an AccessKey). You can obtain it from Device App Management in the Alibaba Cloud console.options: Optional data collection parameters. Default:nil. Available options:
Parameter | Description | Example |
IPv6 | Specifies whether to use an IPv6 domain name to report device information.
| "1" |
CustomUrl | Sets the domain name of the data reporting server. | "https://cloudauth-device.aliyuncs.com" |
CustomHost | Sets the host of the data reporting server. | "cloudauth-device.aliyuncs.com" |
To report to a specific region, set both CustomUrl and CustomHost to the corresponding international endpoint.
Default service endpoints:
Singapore: https://cloudauth-device.ap-southeast-1.aliyuncs.com
China (Hong Kong): https://cloudauth-device.cn-hongkong.aliyuncs.com
Germany (Frankfurt): https://cloudauth-device.eu-central-1.aliyuncs.com
US (Silicon Valley): https://cloudauth-device.us-west-1.aliyuncs.com
initCallback: Initialization callback listener. You can check the initialization status in the callback. Default:nil. For the value range ofcode, see "Status Return Values".Return value: none.
Example
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setValue:@"0" forKey:@"IPv6"]; // Use IPv4
// Set a custom data reporting region
// [options setValue:@"xxx" forKey:@"CustomUrl"]; Set the reporting URL
// [options setValue:@"xxx" forKey:@"CustomHost"]; Set the reporting host
// Standard call (recommended)
[[SecurityDevice sharedInstance] initDevice:@"******" withOptions:options callback:nil];
// Callback call
[[SecurityDevice sharedInstance] initDevice:@"******" withOptions:options callback:^(int code) {
NSString * initResult = [NSString stringWithFormat: @"Initialization result: %d", code];
NSLog(@"%@", initResult);
if (SC_SUCCESS != code) {
NSLog(@"Initialization failed");
} else {
NSLog(@"Initialization successful");
}
}];Obtain the Client Token
Obtain the client token and report it to your business server. The server then calls the Device Risk Detection API to retrieve device risk information.
Wait at least 3 seconds between calling
initDeviceandgetDeviceTokenwith an interval of at least 3 seconds.Pass
bizIdwhen callinggetDeviceTokento bind the token to a unique business ID. Pass the same ID when querying results on the server to verify that the token has not been tampered with.Call
getDeviceTokenon a non-main thread to avoid potential crashes from long call durations.
Function prototype
@interface SecurityDevice : NSObject
- (SecurityToken *)getDeviceToken;
- (SecurityToken *)getDeviceToken:(NSString *)bizId;
@endParameters
bizId: The client business ID. Use it to associate a business ID with a token. Optional.Return value: a
SecurityTokenobject, defined as follows:
@interface SecurityToken : NSObject
/**
* The session operation result.
*/
@property(atomic) int code;
/**
* The token result string.
*/
@property(copy, atomic) NSString *token;
@endReturn values
code: The status code. Use it to determine whether the call succeeded. Return values:FaceSecCode
Code
Description
SC_SUCCESS
10000
The SDK is initialized.
SC_NOT_INIT
10001
The SDK is not initialized.
SC_NOT_PERMISSION
10002
Required permissions are not fully granted.
SC_UNKNOWN_ERROR
10003
An unknown system error occurred.
SC_NETWORK_ERROR
10004
A network error occurred.
SC_NETWORK_ERROR_EMPTY
10005
A network error occurred. The response body is empty.
SC_NETWORK_ERROR_INVALID
10006
The response format from the server is invalid.
SC_PARSE_SRV_CFG_ERROR
10007
Failed to parse the server configuration.
SC_NETWORK_RET_CODE_ERROR
10008
The gateway returned a failure response.
SC_APPKEY_EMPTY
10009
The AppKey is empty.
SC_PARAMS_ERROR
10010
A parameter error occurred.
SC_FGKEY_ERROR
10011
A key calculation error occurred.
SC_APPKEY_ERROR
10012
The AppKey is invalid.
token: The token string returned to the client. Use it to query the Alibaba Cloud Device Risk Detection API.
In a stable network environment, the token string is approximately 600 bytes. In a poor network environment, it is approximately 2.5 KB with the following special prefixes:
International site: connected "U0dfTkxxxx", weak network "U0dfUFxxxx".
If your business encounters a large number of long tokens:
Ensure that the client network is stable.
Ensure an interval of at least 3 seconds between calling
initDeviceandgetDeviceTokenwith an interval of at least 3 seconds.
Re-obtain the token each time you need to query risk information. The token is valid for 7 days.
Example
// We recommend passing bizId to prevent deviceToken tampering.
NSString *bizId = @"1234567890abcdef******";
SecurityToken *deviceToken = [[SecurityDevice sharedInstance] getDeviceToken:bizId];
if (deviceToken == nil || SC_SUCCESS != deviceToken.code) {
NSLog(@"Failed to obtain token. The result cannot be used for risk tag queries.");
} else {
NSLog(@"Successfully obtained token. You can query risk tags. Token: %@", deviceToken.token);
}Send the Token to Your Server
After obtaining the deviceToken, send it to your business server. The server then queries and verifies the risk results.
Complete Code Example
static NSString *USER_APP_KEY = @"<Obtain from the console>";
- (void)viewDidLoad {
[super viewDidLoad];
// Integration example
[self doStandard];
}
- (void)doStandard {
// Initialize the SDK.
// Call only once during the app lifecycle.
[self doInit];
dispatch_async(dispatch_get_global_queue(NULL, NULL), ^{
// This simulates a 2-second wait. Do not add this in production.
[NSThread sleepForTimeInterval:2.0];
// Obtain the token.
[self doGetToken];
});
}
- (void)doInit {
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setValue:@"0" forKey:@"IPv6"]; // Use IPv4
// Set a custom reporting region
// [options setValue:@"https://cloudauth-device.aliyuncs.com" forKey:@"CustomUrl"];
// [options setValue:@"cloudauth-device.aliyuncs.com" forKey:@"CustomHost"];
[[SecurityDevice sharedInstance] initDevice:USER_APP_KEY withOptions:options callback:nil];
}
- (void)doGetToken {
// We recommend passing bizId to prevent deviceToken tampering.
NSString *bizId = @"1234567890abcdef******";
SecurityToken *deviceToken = [[SecurityDevice sharedInstance] getDeviceToken:bizId];
if (deviceToken == nil || SC_SUCCESS != deviceToken.code) {
NSLog(@"Failed to obtain token. The result cannot be used for risk tag queries.");
} else {
NSLog(@"Successfully obtained token. You can query risk tags. Token: %@", deviceToken.token);
}
}To use IDFA or location information, follow Apple's privacy policy: in addition to declaring the corresponding permissions in your app's plist, you must prompt the user for authorization. Ensure your development environment uses Xcode 12 or later.
In scenarios that require risk detection (such as registration or promotional campaigns), obtain the client token and report it to your business server for risk queries.
Call the Device Risk Detection API
After obtaining the deviceToken, send it along with other parameters to the Device Risk Detection API. For details, see the API integration.
FAQ
For frequently asked questions about the Device Fraud Detection SDK, see FAQ.