You can use an SDK to call Visual Intelligence API operations. We recommend integrating the SDK on your server because embedding the AccessKey ID and AccessKey secret directly into your client can lead to security risks. To mitigate these risks, you can use the Security Token Service (STS) to authorize users to call the service.
Background information
Before you make calls from an iOS client, you must obtain temporary access credentials from the Security Token Service (STS). STS is an Alibaba Cloud service that manages temporary access permissions. You can use STS to issue temporary access credentials to users. Users can then use these credentials to call Visual Intelligence API services for a specified period. This method is more secure because you do not need to expose your long-term keys. For more information about how to obtain temporary access credentials, see Obtain temporary identity credentials for a RAM role.
If your file is stored in Object Storage Service (OSS) in the China (Shanghai) region:
If your file is stored in Object Storage Service (OSS) in the China (Shanghai) region, you can use the request signature mechanism to make calls. For more information about the call method, see Scenario 1: The file is in OSS in the China (Shanghai) region. For more information about OSS operations, see Activate OSS.
If the file is a local file or is located at another link:
If you have a local file or a file at another link, you must first convert the file link to an OSS link in the China (Shanghai) region. For more information, see Process file URLs. For more information about the call method, see Scenario 2: The file is local or at an accessible URL.
If you have questions about API access, API operation usage, or other issues related to Visual Intelligence API features, you can contact us by joining the DingTalk group (23109592).
Scenario 1: The file is in OSS in the China (Shanghai) region
If your file is stored in OSS in the China (Shanghai) region, see Request signature to make calls. This topic uses RecognizeBankCard as an example and shows only the key steps and code. For the complete demo, you can download iOSDemo. To call other algorithms, you can modify the code based on the comments and your business requirements.
Interaction flow
Prerequisites
Obtain a temporary STS credential:
Grant permissions:
Before obtaining a temporary STS credential, the caller, which can be a RAM user or RAM role, must be granted the permissions to call STS operations. You can grant permissions by configuring a RAM access policy. For more information about the configuration steps and access policies, see Use a temporary access credential provided by STS to access OSS. You can configure fine-grained authorization policies as needed to prevent excessive permissions. For more information about how to configure fine-grained authorization policies, see Custom policies for Visual Intelligence API.
ImportantFor the following steps, the caller, which can be a RAM user or RAM role, must be granted the AliyunSTSAssumeRoleAccess permission (the permission to call the AssumeRole operation of STS) and the AliyunVIAPIFullAccess permission (the permission to manage the Visual Intelligence API). For this example, we grant the full management permission. In a production environment, we strongly recommend that you configure fine-grained authorization policies as needed to prevent excessive permissions. For more information about how to configure fine-grained authorization policies, see Custom policies for Visual Intelligence API.
Call the AssumeRole operation:
You can use an authorized RAM user or RAM role to call the AssumeRole operation and fill in the required parameters as described in the documentation. For more information about the operation and its usage, see the official documentation for AssumeRole.
Use the STS token:
After you successfully call the AssumeRole operation, you will receive an STS token that contains an
AccessKeyId,AccessKeySecret, andSecurityToken, as shown in the following code. When you call other Alibaba Cloud service operations, replace<ALIBABA_CLOUD_ACCESS_KEY_ID>,<ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and<ALIBABA_CLOUD_SECURITY_TOKEN>in the code with the temporary AccessKeyId,AccessKeySecret, andSecurityTokenfrom the Alibaba Cloud STS token data.
{
"RequestId": "429D9967-C809-5A30-B65E-9B742CF*****",
"AssumedRoleUser": {
"Arn": "acs:ram::175805416243****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "39779315882322****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2024-06-12T03:21:29Z"
}
}Step 1: Configure basic parameters
The following code segment is used to call the "RecognizeBankCard" service of Alibaba Cloud. The code is in the Tool/CallApiClient.m file of the iOSDemo. Replace , <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> with the temporary AccessKeyId, AccessKeySecret, and SecurityToken from the Alibaba Cloud STS token data that you obtained in the Prerequisites section.
/**
<ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> must be replaced with the temporary AccessKeyId, AccessKeySecret, and SecurityToken obtained from the STS token data.
If you use the AccessKey pair of a RAM user, you must also grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html
*/
const NSString* ACCESS_KEY_ID = @"<ALIBABA_CLOUD_ACCESS_KEY_ID>";
const NSString* ACCESS_KEY_SECRET = @"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>";
const NSString* SECURITY_TOKEN = @"<ALIBABA_CLOUD_SECURITY_TOKEN>";Step 2: Call the server-side operation and calculate the signature
The following code segment demonstrates how to calculate a signature and send a request for Visual Intelligence API operations. Signatures are a common security measure for cloud services, ensuring that requests sent to the service are not tampered with and are initiated by legitimate users with the appropriate credentials. For more information about the logic, see Request signature.
The following list describes the purpose and steps of the code segment:
Set API request parameters: Use the
bodyDictdictionary to store the required request parameters, such asAction(the API operation name) andImageURL(the image URL). You also need to add system parameters required for the signature, such asTimestamp(the current timestamp) andSignatureNonce(a unique random value).Generate a signature:
Sort the parameters in ASCII order (
bodyToFormString:).Create a string-to-sign based on the HTTP request method, resource path, and query string.
Use the HMAC-SHA1 algorithm to sign the string-to-sign, and then Base64-encode the result (
hmacSha1:data:).
Construct the request URL: Insert the generated signature and other query parameters into the URL to form the final request URL.
Send the request:
Create an HTTP POST request (
request:).Set the request properties, such as
Content-Type.Use
NSURLSessionto send the request and use a block callback to process the response or error after the request is complete.
Process the response:
If the request is successful, parse the response data and pass the result back through the callback function.
If the request fails, parse the error message and pass the error back through the callback function.
Step 3: Encapsulate the request and send data to the specified Visual Intelligence API operation
The following code segment shows how to call the Alibaba Cloud RecognizeBankCard API operation in an iOS application to detect bank card information. The process involves preparing request parameters, generating a request signature, constructing a request URL, initiating a network request, and processing the response.
The following list describes the purpose and steps of the code segment:
Prepare request parameters: Declare a dictionary of the
NSMutableDictionarytype namedbodyDictto store the required request parameters. These include the following:AccessKeyId: The AccessKey ID required to access Alibaba Cloud API operations.Action: The name of the API operation. In this case, it isRecognizeBankCard, which indicates a call to the Alibaba Cloud bank card detection service.ImageURL: The URL of the bank card image to be detected.SecurityToken: A parameter added to support the use of temporary access credentials. It must be obtained from STS.
Sign the request: All requests to Alibaba Cloud service API operations must be signed to ensure request security. In this example, the
allKeysGotoSignatureWithDict:endpoint:accessSecret:httpMethod:apiVersion:method is used to calculate the signature and construct the final request URL. Information such as the HTTP method (POST), API version, and endpoint are used in the signing process.Construct the request URL: Use the preceding method to calculate the request URL
finalUrlthat contains the signature.Initiate a POST request: Use the custom
request:responseBlock:method to initiate a POST request to the calculatedfinalUrlusingNSURLSession. After the request succeeds or fails, the data or error information is returned to the caller through theblockcallback.Process the response asynchronously: Network requests and response processing are asynchronous to ensure that the main thread is not blocked. The execution of the
blockcallback is scheduled in the dispatch queue of the main thread so that you can safely update the UI or process data.
Step 4: Trigger the button on the page and call the Visual Intelligence API operation
This code shows how to call the recognizeBankCardWithImageUrl:responseBlock: method in the encapsulated CallApiClient class in an iOS application to detect bank card information. This is an Objective-C example that shows how to use the API client at the application layer.
Set the image URL:
Define the variable
imageUrland set it to the URL of the bank card image. This image is stored on Alibaba Cloud OSS and is publicly accessible.
Call the API operation to detect the bank card:
Call the
recognizeBankCardWithImageUrl:responseBlock:static method of theCallApiClientclass, passing an image URL and a callback block that is executed after the request is complete, regardless of whether it succeeds or fails.
Process the response:
In the callback block, first check the
errorobject to determine whether the API call was successful.If an error occurred during the call (
erroris notnil), you must handle the error. Error handling may include logging the error or displaying an error message to the user.If the call is successful (
errorisnil), you can extract the bank card detection result from thedatadictionary returned by the callback. This example shows how to retrieve the bank card number (cardNumber). Based on the API documentation, you may also be able to retrieve other useful information, such as the bank name and card type.
Display the result:
After successfully retrieving the bank card number, the example uses the
alertInfomation:method, which is not implemented in this example and must be defined by you, to display a prompt that shows the bank card number to the user. This is a simple and direct feedback method suitable for rapid prototyping or testing applications.
This code shows the complete process from initiating an API request to receiving and processing the API response. It is a useful reference for understanding how to integrate and use external API operations in a real iOS application. In a complete application, you may also need to consider more error handling and exception scenarios. In addition, for a better user experience, you may want to add a loading indicator during the request to inform the user that a network operation is in progress.
Scenario 2: The file is local or at an accessible URL
If your file is local or at an accessible URL, see Process file URLs to explicitly convert the file to an OSS link in the China (Shanghai) region. Then, you can make the call as described in Scenario 1: The file is in OSS in the China (Shanghai) region. This topic uses RecognizeBankCard as an example and shows only the key steps and code. For the complete demo, you can download iOSDemo. To call other algorithms, you can modify the code based on the comments and your business requirements.
Interaction flow
Prerequisites
Obtain a temporary STS credential:
Grant permissions:
Before obtaining a temporary STS credential, the caller, which can be a RAM user or RAM role, must be granted the permissions to call STS operations. You can grant permissions by configuring a RAM access policy. For more information about the configuration steps, see Use a temporary access credential provided by STS to access OSS. You can configure fine-grained authorization policies as needed to prevent excessive permissions. For more information about how to configure fine-grained authorization policies, see Custom policies for Visual Intelligence API.
ImportantFor the following steps, the caller, which can be a RAM user or RAM role, must be granted the AliyunSTSAssumeRoleAccess permission (the permission to call the AssumeRole operation of STS), the permissions for a RAM role to upload files to OSS, and the AliyunVIAPIFullAccess permission (the permission to manage the Visual Intelligence API). For this example, we grant the full management permission. However, you need to configure fine-grained authorization policies as needed to prevent excessive permissions. For more information about how to configure fine-grained authorization policies, see Custom policies for Visual Intelligence API.
Call the AssumeRole operation:
You can use an authorized RAM user or RAM role to call the AssumeRole operation and fill in the required parameters as described in the documentation. For more information about the operation and its usage, see the official documentation for AssumeRole.
Use the STS token:
After you successfully call the AssumeRole operation, you will receive an STS token that contains an AccessKeyId, AccessKeySecret, and SecurityToken, as shown in the following code. When you call other Alibaba Cloud service operations, replace <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> in the code with the temporary
AccessKeyId,AccessKeySecret, and SecurityToken from the Alibaba Cloud STS token data.
{
"RequestId": "429D9967-C809-5A30-B65E-9B742CF*****",
"AssumedRoleUser": {
"Arn": "acs:ram::175805416243****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "39779315882322****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2024-06-12T03:21:29Z"
}
}Step 1: Configure basic parameters
The following code segment is used to call the "RecognizeBankCard" service of Alibaba Cloud. The code is in the Tool/CallApiClient.m file of the iOSDemo. Replace <ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> with the temporary AccessKeyId, AccessKeySecret, and SecurityToken from the Alibaba Cloud STS token data that you obtained in the Prerequisites section.
The temporary AccessKey ID, AccessKey secret, and security token here are used to avoid exposing your own AccessKey ID and AccessKey secret on the frontend. The temporary STS token obtained in Step 2 is used to upload the file to a temporary OSS bucket to retrieve a URL.
/**
<ALIBABA_CLOUD_ACCESS_KEY_ID>, <ALIBABA_CLOUD_ACCESS_KEY_SECRET>, and <ALIBABA_CLOUD_SECURITY_TOKEN> must be replaced with the temporary AccessKeyId, AccessKeySecret, and SecurityToken obtained from the STS token data.
If you use the AccessKey pair of a RAM user, you must also grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html
*/
const NSString* ACCESS_KEY_ID = @"YOUR_ACCESS_KEY_ID";
const NSString* ACCESS_KEY_SECRET = @"YOUR_ACCESS_KEY_SECRET";
const NSString* SECURITY_TOKEN = @"<ALIBABA_CLOUD_SECURITY_TOKEN>";Step 2: Call the GetOssStsToken operation to obtain a temporary OSS STS token
The following code segment uses an Alibaba Cloud AccessKey ID and AccessKey secret to request a temporary Alibaba Cloud OSS STS token. This STS token allows a user to upload files or data to the official OSS bucket of the Visual Intelligence API. For testing purposes, files are stored in OSS for one day.
The following list describes the purpose and steps of the code segment:
Prepare request data: Use the given
accessKeyandaccessSecretto build a request dictionarybodyDict. This dictionary includes the required operationAction, which is"GetOssStsToken".Sign and build the final URL: Use the provided parameters, including the API endpoint, the recommended POST HTTP request method, and the API version number (
"2020-04-01"), to sign the request and build the final request URL.Send the request: Send the prepared signature and data to the specified API endpoint through a POST request.
Process the response: Process the response returned from the server-side asynchronously. If an error occurs, the callback function passes the error information. If the request is successful, the callback function passes a dictionary containing the STS token data.
In the `recognizeBankCardWithImageUrl` function in the `Tool/CallApiClient.m` file, the `bodyDict[@"Action"]`, `endpoint`, and `apiVersion` parameters, and the `bodyDict[@"ImageURL"]` line are business parameters.
For example, if you want to use the universal segmentation feature, the SegmentCommonImage API documentation shows that this feature belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage. You need to change the endpoint to `imageseg.cn-shanghai.aliyuncs.com`, change `bodyDict[@"Action"]` to `SegmentCommonImage`, and set `apiVersion` to `2019-12-30`. The parameter name `bodyDict[@"ImageURL"]` does not need to be changed. When you retrieve the result, you need to retrieve the `ImageURL`, which is the URL of the segmented image, not a bank card number.
Step 3: Use the temporary OSS STS token to upload the file to the official Visual Intelligence API OSS bucket
The following code segment uploads image data to Alibaba Cloud OSS using a temporary STS token for authentication and authorization.
The following list describes the purpose and steps of the code segment:
Obtain an STS token through
CallApiClient: Use the provided AccessKey ID (accessKeyId), AccessKey secret (accessKeySecret), and a possibly existingsecurityTokento request an STS token fromCallApiClient.Initialize the OSS client: Use the retrieved temporary credential information to create an OSS client (
OSSClient) instance for subsequent OSS operations. The client configuration (OSSClientConfiguration) includes setting the number of retries, request timeout, and maximum resource transfer time.Set the upload request: Create an
OSSPutObjectRequestobject to specify the details of the file to be uploaded. The file is uploaded to the fixed bucket ("viapi-customer-temp"), and the object key (objectKey) is composed of the AccessKey ID and a random UUID to ensure uniqueness.Execute the upload task: Call the
putObject:method to upload the image data. This process is asynchronous.Retrieve the URL of the uploaded file: After the upload is successful, use the presigned URL feature of the OSS client (
presignConstrainURLWithBucketName:withObjectKey:withExpirationInterval:) to retrieve the access URL of the uploaded file.Return the URL through a callback: Execute the callback function
blockto pass the URL of the uploaded file to the caller, or return an error message if the upload fails.
For this step, you need to import `libresolv.tbd` and `AliyunOSSiOS.framework` in Frameworks. `libresolv.tbd` is a system library. For information about how to compile and retrieve `AliyunOSSiOS.framework`, see Install the OSS iOS SDK.
Step 4: After uploading, obtain the OSS URL and call the Visual Intelligence API operation
The following code segment is used to retrieve the URL after uploading a file to OSS and then call a Visual Intelligence API operation. The procedure is the same as in Scenario 1: The file is in OSS in the China (Shanghai) region. Each step is encapsulated in the code. For the complete sample code, you can download iOSDemo.
The following list describes the purpose and steps of the code segment:
Set parameters: Build a dictionary
bodyDictto set the required API parameters. These include the following:AccessKeyIdandAccessKeySecret: Credentials for identity verification.SecurityToken: A temporary security credential, usually used with STS.ImageURL: The URL of the bank card image to be detected.Action: Specifies the API feature to be called. In this case, it is"RecognizeBankCard", which means to detect a bank card.
Prepare the API request:
The code builds a signed final URL
finalUrl. This process includes setting the API endpoint, the recommended POST method, the API version, and generating a signature based on the AccessKey pair, API endpoint, and other parameters.
Execute the API request: Send a POST request to the built
finalUrl. This is implemented by therequest:responseBlock:method. The specific implementation of this method is not shown, but you can assume that it is responsible for sending the request to the server and processing the response.Process the response: The response to the request is processed through the asynchronous callback
responseBlock. If the request is successful, the API response data, such as the detected bank card information, is returned to the caller throughblock(responseObject, nil). If an error occurs during the request, the error is returned to the caller throughblock(nil, error).
In the `Tool/CallApiClient.m` file, the `recognizeBankCardWithImageUrl` function's `bodyDict[@"Action"]`, `endpoint`, and `apiVersion` parameters, and the `bodyDict[@"ImageURL"]` line are business parameters.
For example, if you want to use the universal segmentation feature, the SegmentCommonImage API documentation shows that this feature belongs to the image segmentation category (imageseg20191230) and its name is SegmentCommonImage. You need to change the endpoint to imageseg.cn-shanghai.aliyuncs.com, change bodyDict[@"Action"] to SegmentCommonImage, and set apiVersion to 2019-12-30. The parameter name bodyDict[@"ImageURL"] does not need to be changed. When you retrieve the result, you need to retrieve the ImageURL, which is the URL of the segmented image, not a bank card number.