All Products
Search
Document Center

Mobile Platform as a Service:Use SDKs

Last Updated:Nov 03, 2025

RPC-related modules are APMobileNetwork.framework and MPMglsAdapter. We recommend that you use the APIs in MPMglsAdapter.

This topic describes how to use the mobile gateway SDK by performing the following steps:

  1. Initializing the gateway service

  2. Generating RPC Code

  3. Send reque

  4. Request custom configurations

  5. Custom RPC interceptors

  6. Data encryption

  7. Data signature

Initialize the gateway service

Call the following method to initialize the gateway service:

[MPRpcInterface initRpc];

Precautions for upgrading an earlier version

After the 10.1.32 version, you no longer need to add Category files of the DTRpcInterface class. The middle layer will implement packaging to read from the meta.config. After the version is upgraded, check whether the configuration of the old version exists in the project. If yes, remove it. Below is the Category file for the DTRpcInterface classes that should be removed for the new version.

gateway

Generate RPC code

After the app is connected to the background service in the mobile gateway console, you can download the RPC code of the client. For more information, see Generate code.

The structure of the downloaded RPC code is as follows:

code structure

Where:

  • RPCDemoCloudpay_accountClient is the RPC configuration.

  • RPCDemoAuthLoginPostReq is the request model.

  • RPCDemoLoginResult is the response model.

Send Request

RPC requests must be called in a sub-thread. You can use the sub-thread call interface encapsulated by the MPRpcInterface in the middle layer. The callback method is the main thread by default. The sample code is as follows:

- (void)sendRpc
{
    __block RPCDemoLoginResult *result = nil;
    [MPRpcInterface callAsyncBlock:^{
        @try
        {
            RPCDemoLoginRequest *req = [[RPCDemoLoginRequest alloc] init];
            req.loginId = @"alipayAdmin";
            req.loginPassword = @"123456";
            RPCDemoAuthLoginPostReq *loginPostReq = [[RPCDemoAuthLoginPostReq alloc] init];
            loginPostReq._requestBody = req;
            RPCDemoCloudpay_accountClient *service = [[RPCDemoCloudpay_accountClient alloc] init];
            result = [service authLoginPost:loginPostReq];
        }
        @catch (NSException *exception) {
            NSLog(@"%@", exception);
            NSError *error = [userInfo objectForKey:@"kDTRpcErrorCauseError"]; // Obtain the exception details.
            NSInteger code=error.code; // Obtain the error code of the exception details.
        }
    } completion:^{
        NSString *str = @"";
        if (result && result.success) {
            str = @"Logon succeeded";
        } else {
            str = @"Logon failed";
        }

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:str message:nil delegate:nil
                                              cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
        [alert show];
    }];
}
Note

Safely handle Objective-C exceptions in Swift

Background

Swift's error handling mechanism (do-catch) differs from Objective-C's exception handling mechanism (@try-@catch) at the underlying level. Therefore, Swift code cannot directly catch NSException thrown by Objective-C code, which can cause App crashes in mixed programming.

Solution

To address this issue and ensure App stability, we provide the APRpcExceptionCatch tool. Its safeExecuteTry method encapsulates Objective-C's @try-@catch logic, allowing you to safely execute RPC calls in a Swift environment.

If the Objective-C code throws an exception during execution, safeExecuteTry will catch it and return it as a DTRpcException object. If the code executes normally, it will return nil.

Version

Supported in baseline versions 10.2.3.66 and above.

Sample Code

import MBProgressHUD
import APMobileNetwork

private func performGetIdRpcCall() {
    
    // 1. Display a loading indicator (the beginning of the original executeRpc)
    MBProgressHUD.showAdded(to: self.view, animated: true)
    
    // 2. Define variables to receive results and errors
    var response: MPDemoUserInfo? // Replace the generic type T with the specific type MPDemoUserInfo
    var rpcError: DTRpcException?
    
    // 3. Asynchronously execute RPC calls (originally DTRpcAsyncCaller.callAsyncBlock)
    DTRpcAsyncCaller.callAsyncBlock({
        
        // 3.1. Safely executing the actual RPC call in a background thread
        rpcError = APRpcExceptionCatch.safeExecuteTry {
            // Here are the contents of the original 'call' closure
            let client = MPDemoRpcDemoClient()
            // Assign the result to the response variable
            response = client.getIdGet(self.getRequest()) 
        }
        
    }, completion: {
        
        // 4. Process the post-completion logic in the main thread
        DispatchQueue.main.async {
            
            // 4.1. Hide the loading indicator
            MBProgressHUD.hide(for: self.view, animated: true)
            
            // 4.2. Check if RPC call has errors
            if let exception = rpcError {
                // If there is an error, construct and display the error message
                var errorMsg: String
                if exception.code.rawValue == 0 {
                    if let realError = exception.userInfo?["kDTRpcErrorCauseError"] as? NSError {
                        let errorString = "Error: [Domain: \(realError.domain), Code: \(realError.code), Description: \(realError.localizedDescription)]"
                        errorMsg = "Rpc Exception: \(errorString)"
                    } else {
                        let cause = exception.userInfo?["kDTRpcErrorCauseError"]
                        errorMsg = "Rpc Exception code: \(exception.code), no real error: \(cause ?? "nil")"
                    }
                } else {
                    errorMsg = "Rpc Exception code: \(exception.code)"
                }
                
                // Display error message
                self.showErrorToast(message: errorMsg)
                
            } else {
                // 4.3. If the call is successful, process the returned data
                //Here are the contents of the original 'success' closure
                self.showAlert(title: "Return data", message: response?.description)
            }
        }
    })
}

Request custom configurations

The RPC request method description DTRpcMethod records the RPC request method name, parameters, and return type.

  • If you do not need to sign the request, you can set the DTRpcMethod signCheck attribute to NO.

    -(MPDemoUserInfo *) dataPostSetTimeout:(MPDemoPostPostReq *)requestParam
    {
      DTRpcMethod *method = [[DTRpcMethod alloc] init];
      method.operationType = @"com.antcloud.request.post";
      method.checkLogin =  NO ;
      method.signCheck =  NO ;
      method.returnType =   @"@\"MPDemoUserInfo\"";
    
      return [[DTRpcClient defaultClient] executeMethod:method params:@[ ]];
    }
  • If you need to set the timeout period, you can configure the DTRpcMethod timeoutInterval properties.

    -(MPDemoUserInfo *) dataPostSetTimeout:(MPDemoPostPostReq *)requestParam
    {
      DTRpcMethod *method = [[DTRpcMethod alloc] init];
      method.operationType = @"com.antcloud.request.post";
      method.checkLogin =  NO ;
      method.signCheck =  YES ;
       method.timeoutInterval = 1; // This timeout period is the time when the client receives the response from the gateway. The timeout period configured by the server is the time when the backend business system returns the response. The default value is 20s. If the setting is less than 1, it is invalid.
      method.returnType =   @"@\"MPDemoUserInfo\"";
    
      return [[DTRpcClient defaultClient] executeMethod:method params:@[ ]];
    }
  • If you need to add Header to all APIs, you can use the following extension method. DTRpcClient

    -(MPDemoUserInfo *) dataPostAddHeader:(MPDemoPostPostReq *)requestParam
    {
      DTRpcMethod *method = [[DTRpcMethod alloc] init];
      method.operationType = @"com.antcloud.request.postAddHeader";
      method.checkLogin =  NO ;
      method.signCheck =  YES ;
      method.returnType =   @"@\"MPDemoUserInfo\"";
    
      // Add a header to the API.
      NSDictionary *customHeader = @{@"testKey": @"testValue"};
      return [[DTRpcClient defaultClient] executeMethod:method params:@[ ] requestHeaderField:customHeader responseHeaderFields:nil];
    }
  • If you want to add Header to all APIs, use interceptors. For more information, see Use interceptors. For more information, see Sample code.

  • The checkLogin attribute is used for interface session verification and needs to be completed in conjunction with the gateway console. The default setting is NO.

Custom RPC Interceptor

Based on business requirements, you may need to perform logic processing before the RPC is sent or after the RPC is processed. The RPC module provides an interceptor mechanism to handle such requirements.

Custom interceptor

Create interceptors and implement protocol -<DTRpcInterceptor> methods to process RPC requests before and after operations.

@interface HXRpcInterceptor : NSObject<DTRpcInterceptor>

@end

@implementation HXRpcInterceptor

- (DTRpcOperation *)beforeRpcOperation:(DTRpcOperation *)operation{
    // TODO
    return operation;
}

- (DTRpcOperation *)afterRpcOperation:(DTRpcOperation *)operation{
   // TODO
   return operation;
}
@end

Register an interceptor

You can call the extension interface of the middle layer to register custom subinterceptors in the interceptor container.

HXRpcInterceptor *mpTestIntercaptor = [[HXRpcInterceptor alloc] init]; // Custom subinterceptor
    [MPRpcInterface addRpcInterceptor:mpTestIntercaptor];

Data encryption

RPC provides various data encryption configuration features. For more information, see Data encryption.

Data signature (supported in 10.2.3)

The 10.2.3 baseline RPC provides a variety of data signature configuration features. 10.2.3 The baseline upgraded the wireless bodyguard SDK to support the national secret signature. After the upgrade, the wireless bodyguard picture needs to be replaced with V6 version to use this baseline.

The 10.1.68 baseline defaults to the V5 version. Follow these steps to use the plug-in to generate a V6 image and replace the original yw_1222.jpg wireless bodyguard image.

  1. Install the mPaaS command-line tool. The command-line tool is included in the plug-in installation. You can set N by removing the Xcode signature.

  2. Use the following command line to generate a new wireless bodyguard image.

    mpaas inst sgimage -c /path/to/Ant-mpaas-0D4F511111111-default-IOS.config -V 6 -t 1 -o /path/to/output --app-secret sssssdderrff --verbose
    Note

    Replace the config file directory, target file directory, and appsecret parameters with actual values.

  3. If you want the wireless bodyguard to support the national secret function, please follow the following code to configure the category code to set the signature algorithm, the default configuration is not MPAASRPCSignTypeDefault, the signature algorithm is MD5.

    Optional values of the signature algorithm are as follows:

    • MD5: MPAASRPCSignTypeDefault (default)

    • SHA256: MPAASRPCSignTypeSHA256

    • HMACSHA256: MPAASRPCSignTypeHMACSHA256

    • SM3: MPAASRPCSignTypeSM3

    Sample code:

    #import <APMobileNetwork/DTRpcInterface.h>
    
    @interface DTRpcInterface (mPaaSDemo)
    
    @end
    
    @implementation DTRpcInterface (mPaaSDemo)
    
    - (MPAASRPCSignType)customRPCSignType
    {
        return MPAASRPCSignTypeSM3;
    }
    
    @end

Links