Skip to content

UniApp Application Integration


Prerequisites

Note: If you have enabled the RUM Headless service, the prerequisites have been automatically configured for you. You can directly proceed with integrating your application.

Application Integration

The current UniApp version supports Android and iOS platforms. Log in to the Guance console, go to the Synthetic Tests page, click on the top-left corner [Create], and start creating a new application.

Installation

Local Use

Source Code Address: https://github.com/GuanceCloud/datakit-uniapp-native-plugin

Demo Address: https://github.com/GuanceCloud/datakit-uniapp-native-plugin/Hbuilder_Example

SDK package structure description:

|--datakit-uniapp-native-plugin
  |-- Hbuilder_Example            // GCUniPlugin plugin example project
      |-- nativeplugins           // Example project's local plugin folder
          |-- GCUniPlugin         // ⭐️ GCUniPlugin native plugin package ⭐️
          |   |-- android         // Stores dependencies and resource files required by the android plugin
          |   |-- ios             // Stores dependencies and resource files required by the ios plugin
          |   |-- package.json    // Plugin configuration file
      |-- GCPageMixin.js          // js used for automatic view capture, GCPageMixin.js works together with GCWatchRouter.js
      |-- GCWatchRouter.js        // js used for automatic view capture, GCPageMixin.js works together with GCWatchRouter.js
      |-- GCPageViewMixinOnly.js  // js used for automatic view capture, GCPageViewMixinOnly.js can be used independently
      |-- GCRequest.js            // js used for resources and traces, provides APM and network request monitoring capabilities
  |-- UniPlugin-Android           // Main Android plugin development project
  |-- UniPlugin-iOS               // Main iOS plugin development project

Configure the GCUniPlugin folder under the "nativeplugins" directory of your uni_app project. Additionally, in the "App Native Plugin Configuration" section of the manifest.json file, click "Select Local Plugin," then choose the GCUniPlugin plugin from the list:

img

Note: After saving, you need to submit it for cloud packaging (creating a custom base) also falls under cloud packaging before the plugin takes effect.

For more details, refer to: Using Local Plugins in HBuilderX, Custom Base

Marketplace Plugin Method

(Not provided)

uni Mini Program SDK Installation

Development Debugging and wgt Release Usage

  • When developing and debugging the uni mini program SDK, use the Local Use method to integrate GCUniPlugin.

  • When packaging the uni mini program SDK into a wgt file for the host App, the host App must import the GCUniPlugin dependency library (including the Native SDK library) and register the GCUniPlugin Module.

Operations required by the host App:

iOS

  • Add the GCUniPlugin dependency library

    In the Xcode project, select the project name from the left-hand directory, then navigate to TARGETS -> Build Phases -> Link Binary With Libaries and click the "+" button. In the popup window, click Add Other -> Add Files..., then open the GCUniPlugin/ios/ dependency library directory, select both FTMobileSDK.xcframework and Guance_UniPlugin_App.xcframework, and click the open button to add the dependency libraries to the project.

    When SDK Version < 0.2.0: In TARGETS -> General -> Frameworks,Libaries,and Embedded Content, find FTMobileSDK.xcframework and change its Embed method to Embed & sign.

  • Register the GCUniPlugin Module:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ....
      // Register GCUniPlugin module
    [WXSDKEngine registerModule:@"GCUniPlugin-MobileAgent" withClass:NSClassFromString(@"FTMobileUniModule")];
    [WXSDKEngine registerModule:@"GCUniPlugin-RUM" withClass:NSClassFromString(@"FTRUMModule")];
    [WXSDKEngine registerModule:@"GCUniPlugin-Logger" withClass:NSClassFromString(@"FTLogModule")];
    [WXSDKEngine registerModule:@"GCUniPlugin-Tracer" withClass:NSClassFromString(@"FTTracerModule")];  
      return YES;
    }

Android

  • Add the GCUniPlugin dependency library

  • Method One: Copy the ft-native-[version].aar, ft-sdk-[version].aar, and gc-uniplugin-[last-version].aar files from the GCUniPlugin/android/ folder to the libs folder of your project, and modify the build.gradle file to include the dependencies.

  • Method Two: Use the Gradle Maven remote repository configuration method. Refer to the configuration instructions for UniAndroid-Plugin project configuration.
  dependencies {
      implementation files('libs/ft-native-[version].aar')
      implementation files('libs/ft-sdk-[version].aar')
      implementation files('libs/gc-uniplugin-[last-version].aar')
      implementation 'com.google.code.gson:gson:2.8.5'
  }   
  • Register the GCUniPlugin Module:
  public class App extends Application {
      @Override
      public void onCreate() {
          super.onCreate();
          try {
            // Register GCUniPlugin module
              WXSDKEngine.registerModule("GCUniPlugin-Logger", FTLogModule.class);
              WXSDKEngine.registerModule("GCUniPlugin-RUM", FTRUMModule.class);
              WXSDKEngine.registerModule("GCUniPlugin-Tracer", FTTracerModule.class);
              WXSDKEngine.registerModule("GCUniPlugin-MobileAgent", FTSDKUniModule.class);
          } catch (Exception e) {
              e.printStackTrace();
          }
          ......
      }
  }

Mixed Use of UniApp SDK and Native SDK

  • During the process of adding the GCUniPlugin dependency library, the Native SDK is already added to the host project, so you can directly call the methods of the Native SDK.

  • SDK Initialization

    When using mixed mode, only initialize the Native SDK within the host App. No additional initialization configuration is required within the uni mini program; you can directly call the methods provided by the UniApp SDK.

    Refer to the SDK initialization methods for the host App: iOS SDK Initialization Configuration, Android SDK Initialization Configuration.

    Note: The host App must complete the SDK initialization before loading the uni mini program to ensure that the SDK is fully ready before calling any other methods of the SDK.

  • Additional Configuration for Android Integration:

    Configure Gradle Plugin ft-plugin to collect app startup events and network request data, as well as Android Native related events (page transitions, click events, Native network requests, WebView data).

SDK Initialization

Basic Configuration

// Configure in App.vue
<script>
    var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
    export default {
        onLaunch: function() {
            guanceModule.sdkConfig({
                'datakitUrl': 'your datakitUrl',
                'debug': true,
                'env': 'common',
                'globalContext': {
                    'custom_key': 'custom value'
                }
            })
        }
    }
</script>
<style>
</style>
Parameter Name Parameter Type Required Parameter Description
datakitUrl string Yes Deployment URL address for reporting (Datakit). Example: http://10.0.0.1:9529, port defaults to 9529. The device installing the SDK must be able to access this address. Note: Choose between datakitUrl and datawayUrl
datawayUrl string Yes Public Dataway reporting URL address, obtained from the [User Analysis] application. Example: https://open.dataway.url. The device installing the SDK must be able to access this address. Note: Choose between datakitUrl and datawayUrl
clientToken string Yes Authentication token, needs to be used simultaneously with datawayUrl
debug boolean No Whether to allow printing of Debug logs, default false
env string No Environment, default prod, any character, recommend using single words such as test etc.
service string No Sets the name of the associated business or service. Default: df_rum_ios, df_rum_android
globalContext object No Adds custom tags
offlinePakcage boolean No Supported only by Android, whether to use offline packaging or uni mini program, default false. Detailed explanation see Difference between Android Cloud Packaging and Offline Packaging
autoSync boolean No Whether to automatically synchronize data to the server after collection. Default YES. When set to NO, use the flushSyncData method to manage data synchronization manually
syncPageSize number No Sets the number of entries per synchronization request. Range [5, ). Note: Larger request entry counts mean higher computational resource usage for data synchronization, default is 10
syncSleepTime number No Sets the interval time for synchronization. Range [0,5000], default not set
enableDataIntegerCompatible boolean No Suggest enabling if coexistence with web data is needed. This configuration handles web data type storage compatibility issues. Automatically enabled for versions 0.2.1 and later
compressIntakeRequests boolean No Compress uploaded synchronized data using deflate compression, default off. Supported by SDK versions 0.2.0 and above
enableLimitWithDbSize boolean No Enable limiting data size using db, default 100MB, unit Byte. Larger databases increase disk pressure, default not enabled. Note: Enabling this will make Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount ineffective. Supported by SDK versions 0.2.0 and above
dbCacheLimit number No DB cache limit size. Range [30MB,), default 100MB, unit byte, supported by SDK versions 0.2.0 and above
dbDiscardStrategy string No Sets the data discard rule in the database. Discard strategy: discard discards new data (default), discardOldest discards old data. Supported by SDK versions 0.2.0 and above

RUM Configuration

var rum = uni.requireNativePlugin("GCUniPlugin-RUM");
rum.setConfig({
  'androidAppId':'YOUR_ANDROID_APP_ID',
  'iOSAppId':'YOUR_IOS_APP_ID',
  'errorMonitorType':'all', // or 'errorMonitorType':['battery','memory']
  'deviceMonitorType':['cpu','memory']// or  'deviceMonitorType':'all'
})
Parameter Name Parameter Type Required Description
androidAppId string Yes App ID, requested during monitoring
iOSAppId string Yes App ID, requested during monitoring
samplerate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope applies to all View, Action, LongTask, Error data under the same session_id
enableNativeUserAction boolean No Whether to track Native Action, Button click events, pure uni-app applications are recommended to disable, default is false, Android cloud packaging does not support
enableNativeUserResource boolean No Whether to perform Native Resource automatic tracking, default is false, Android cloud packaging does not support. Since uniapp network requests on iOS use system APIs, enabling this will collect all resource data on iOS, at which point manual collection on iOS should be disabled to prevent duplicate data collection
enableNativeUserView boolean No Whether to perform Native View automatic tracking, pure uni-app applications are recommended to disable, default is false
errorMonitorType string/array No Additional error monitoring types: all, battery, memory, cpu
deviceMonitorType string/array No Additional page monitoring types: all, battery (only supported on Android), memory, cpu, fps
detectFrequency string No Page monitoring frequency: normal (default), frequent, rare
globalContext object No Custom global parameters, special key: track_id (used for tracking features)
enableResourceHostIP boolean No Whether to collect the IP address of the requested target domain. Scope: Only affects default collection when enableNativeUserResource is set to true. iOS: Supported on >= iOS 13. Android: Okhttp caches IP addresses for the same domain, so only one generation occurs if the IP does not change for the same OkhttpClient.
enableTrackNativeCrash boolean No Whether to enable Android Java Crash and OC/C/C++ crash monitoring, default is false
enableTrackNativeAppANR boolean No Whether to enable Native ANR monitoring, default is false
enableTrackNativeFreeze boolean No Whether to collect Native Freeze
nativeFreezeDurationMs number No Set the threshold for collecting Native Freeze stalls, range [100,), unit milliseconds. Default on iOS is 250ms, on Android is 1000ms
rumDiscardStrategy string No Discard strategy: discard discards new data (default), discardOldest discards old data
rumCacheLimitCount number No Maximum number of locally cached RUM entries [10_000,), default 100_000

Log Configuration

var logger = uni.requireNativePlugin("GCUniPlugin-Logger");
logger.setConfig({
  'enableLinkRumData':true,
  'enableCustomLog':true,
  'discardStrategy':'discardOldest'
})
Parameter Name Parameter Type Required Parameter Description
samplerate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1
enableLinkRumData boolean No Whether to link with RUM
enableCustomLog boolean No Whether to enable custom logs
discardStrategy string No Log discard strategy: discard discards new data (default), discardOldest discards old data
logLevelFilters array No Log level filters, array needs to fill in log levels: info prompt, warning warning, error error, critical, ok recovery
globalContext object No Custom global parameters
logCacheLimitCount number No Maximum number of locally cached log entries [1000,), larger logs mean greater disk caching pressure, default is 5000

Trace Configuration

var tracer = uni.requireNativePlugin("GCUniPlugin-Tracer");
tracer.setConfig({
  'traceType': 'ddTrace'
})
Parameter Name Parameter Type Required Parameter Description
samplerate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
traceType string No Trace type: ddTrace (default), zipkinMultiHeader, zipkinSingleHeader, traceparent, skywalking, jaeger
enableLinkRUMData boolean No Whether to link with RUM data, default false
enableNativeAutoTrace boolean No Whether to enable native network automatic tracing iOS NSURLSession , Android OKhttp, default false, Android cloud packaging does not support. Since uniapp network requests on iOS use system APIs, enabling this allows automatic tracking of iOS network requests initiated by uniapp, at which point manual tracing on iOS should be disabled to prevent incorrect association of traces with RUM data.

RUM User Data Tracking

var rum = uni.requireNativePlugin("GCUniPlugin-RUM");

Action

API - startAction

Start a RUM Action.

RUM binds this Action to possible triggered Resource, Error, and LongTask events. Avoid adding multiple times within 0.1 seconds. Only one Action can be associated with the same View at the same time, and previous Actions that have not ended will discard newly added Actions. Adding Actions via addAction is unaffected.

rum.startAction({
  'actionName': 'action name',
  'actionType': 'action type'
})
Parameter Name Parameter Type Required Parameter Description
actionName string Yes Event name
actionType string Yes Event type
property object No Event context (optional)

API - addAction

Add an Action event. These data cannot be associated with Error, Resource, or LongTask data and do not have a discard logic.

rum.addAction({
  'actionName': 'action name',
  'actionType': 'action type'
})
Parameter Name Parameter Type Required Parameter Description
actionName string Yes Event name
actionType string Yes Event type
property object No Event context (optional)

View

  • Automatic Collection

Method One: Just configure App.vue and the first page entered by the application. Refer to the example project Hbuilder_Example/App.vue and Hbuilder_Example/pages/index/index.vue in the SDK package of the GCUniPlugin plugin.

// step 1. Find GCWatchRouter.js and GCPageMixin.js files in the SDK package and add them to your project
// step 2. Add Router monitoring in App.vue as follows:
<script>
  import WatchRouter from '@/GCWatchRouter.js'
  export default {
    mixins:[WatchRouter], //<--- Notice
  }
</script>
// step 3. Add pageMixin in the first displayed page as follows:
<script>
  import GCPageMixin from '../../GCPageMixin.js';
  export default {
    data() {
      return {}
    },
    mixins:[GCPageMixin], //<--- Notice
  }
</script>

Method Two: Apply to each page that needs monitoring and use separately from GCWatchRouter.js. Refer to the example project Hbuilder_Example/pages/rum/index.vue in the SDK package of the GCUniPlugin plugin.

//Find GCPageViewMixinOnly.js in the SDK package and add it to your project
<script>
import { rumViewMixin } from '../../GCPageViewMixinOnly.js';
export default {
    data() {
        return {            
        }
    },
    mixins:[rumViewMixin], //<--- Notice
    methods: {}
}
</script>
  • Manual Collection
// Manually collect the lifecycle of Views
// step 1 (optional)
rum.onCreateView({
  'viewName': 'Current Page Name',
  'loadTime': 100000000,
})
// step 2
rum.startView('Current Page Name')
// step 3  
rum.stopView()         

API - onCreateView

Record creation duration of pages

Field Type Required Description
viewName string Yes Page name
loadTime number Yes Page loading time (nanosecond-level timestamp)

API - startView

Enter page

Field Type Required Description
viewName string Yes Page name
property object No Event context (optional)

API - stopView

Leave page

Field Type Required Description
property object No Event context (optional)

Error

  • Automatic Collection
/// Use uniapp error listening function, triggered when script errors or API calls fail
<script>
  var rum = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
  var appState = 'startup';
  // Can only listen in App.vue
  export default {
    onShow: function() {
      appState = 'run'
    },
    onError:function(err){   
      if (err instanceof Error){
        rum.addError({
          'message': err.message,
          'stack': err.stack,
          'state': appState,
        })
      }else if(err instanceof String){
        rum.addError({
          'message': err,
          'stack': err,
          'state': appState,
        })
      }
  }
</script>
  • Manual Collection
// Manually add
rum.addError({
  'message': 'Error message',
  'stack': 'Error stack',
})

API - addError

Add Error event

Field Type Required Description
message string Yes Error information
stack string Yes Stack information
state string No App running state (unknown, startup, run)
type string No Error type, default uniapp_crash
property object No Event context (optional)

Resource

  • Automatic Collection

SDK provides the callable method gc.request, inheriting the uni.request network request method, which can replace uni.request for use.

Replacement Method

+ import gc from './GCRequest.js'; 
- uni.request({
+ gc.request({
  //...
});

Usage Example

//Find GCRequest.js in the SDK package and add it to your project
import gc from './GCRequest.js';
gc.request({
  url: requestUrl,
  method: method,
  header: header,
  filterPlatform:["ios"], 
  timeout:30000,
  success(res)  {
    console.log('success:' + JSON.stringify(res))
  },
  fail(err) {
    console.log('fail:' + JSON.stringify(err))
  },
  complete() {
    console.log('complete:' + JSON.stringify(err))
  }
});

Extra Field Type Required Description
filterPlatform array No When the enableNativeUserResource feature is enabled, uniapp automatically collects network request data initiated through system APIs on iOS. To avoid duplicate data collection, you can add the filterPlatform: ["ios"] parameter when using gc.request to block manual data collection on iOS platforms.
  • Manual Collection

Manually implement by calling startResource,stopResource,addResource, reference the implementation method of GCRequest.js

API - startResource

HTTP request starts

Field Type Required Description
key string Yes Request unique identifier
property object No Event context (optional)

API - stopResource

HTTP request ends

Field Type Required Description
key string Yes Request unique identifier
property object No Event context (optional)

API - addResource

Parameter Name Parameter Type Required Parameter Description
key string Yes Request unique identifier
content content object Yes Request-related data

content object

Prototype Parameter Type Parameter Description
url string Request url
httpMethod string HTTP method
requestHeader object Request headers
responseHeader object Response headers
responseBody string Response result
resourceStatus string Request status code

Logger Log Printing

var logger = uni.requireNativePlugin("GCUniPlugin-Logger");
logger.logging({
  'content':`Log content`,
  'status':status
})

API - logging

Field Type Required Description
content string Yes Log content, can be json string
status string Yes Log level
property object No Event context (optional)

Log Levels

String Meaning
info Prompt
warning Warning
error Error
critical Critical
ok Recovery

Tracer Network Trace Tracking

  • Automatic Collection

Use gc.request for request calls, which automatically adds Propagation Headers. Refer to Resource

  • Manual Collection
// Example using uni.request for network requests
var tracer = uni.requireNativePlugin("GCUniPlugin-Tracer");
let key = Utils.getUUID();// Reference Hbuilder_Example/utils.js
var header = tracer.getTraceHeader({
      'key': key,
      'url': requestUrl,
})
uni.request({
        url: requestUrl,
        header: header,
        success() {

        },
        complete() {

        }
});

API - getTraceHeader

Get the request headers required for trace and add them to the HTTP request headers.

Field Type Required Description
key string Yes Request unique identifier
url string Yes Request URL

Return Value Type: object

Binding and Unbinding User Information

var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");

guanceModule.bindRUMUserData({
  'userId':'Test userId',
  'userName':'Test name',
  'userEmail':'test@123.com',
  'extra':{
    'age':'20'
  }
})

guanceModule.unbindRUMUserData()

API - bindRUMUserData

Bind user information:

Field Type Required Description
userId string Yes User Id
userName string No User name
userEmail string No User email
extra object No User extra information

API - unbindRUMUserData

Unbind the current user.

Closing the SDK

var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
guanceModule.shutDown()

API - shutDown

Close the SDK.

Clearing SDK Cache Data

var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
guanceModule.clearAllData()

API - clearAllData

Clear all data that has not yet been uploaded to the server.

Actively Synchronizing Data

var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
guanceModule.flushSyncData()

API - flushSyncData

When configuring guanceModule.sdkConfig as true, no additional operations are required, and the SDK will automatically synchronize.

When configuring guanceModule.sdkConfig as false, actively trigger the data synchronization method to synchronize data.

WebView Data Monitoring

WebView data monitoring requires integrating the Web Monitoring SDK on the accessed page.

Android only supports offline packaging and uni mini programs

Adding Custom Tags

var guanceModule = uni.requireNativePlugin("GCUniPlugin-MobileAgent");
ftMobileSDK.appendGlobalContext({
          'ft_global_key':'ft_global_value'
})
ftMobileSDK.appendRUMGlobalContext({
          'ft_global_rum_key':'ft_global_rum_value'
})
ftMobileSDK.appendLogGlobalContext({
          'ft_global_log_key':'ft_global_log_value'
})                

API - appendGlobalContext

Add custom global parameters. Applies to RUM, Log data

Field Type Required Description
None object Yes Custom global parameters

API - appendRUMGlobalContext

Add custom RUM global parameters. Applies to RUM data

Field Type Required Description
None object Yes Custom global RUM parameters

API - appendLogGlobalContext

Add custom RUM, Log global parameters. Applies to Log data

Field Type Required Description
None object Yes Custom global Log parameters

Common Issues

Using the Main Project UniPlugin-iOS for Plugin Development

Download the UniApp Offline Development SDK

Based on the version number of the HBuilderX tool used for uni-app development, download the SDK package required for plugin development.

SDK package structure description

|--iOSSDK   
    |-- HBuilder-Hello              // uni-app offline packaging project
    |-- HBuilder-uniPluginDemo      // Main uni-app plugin development project (the project used in this document)
    |-- SDK                         // Dependency libraries and resource files

Drag the dependency libraries and resource files SDK folder into the UniPlugin-iOS folder. After dragging, the directory structure should look like this.

|-- UniPlugin-iOS
    |-- HBuilder-uniPluginDemo      // Main uni-app plugin development project (the project used in this document)
    |-- SDK                         // Dependency libraries and resource files

For more details, refer to iOS Plugin Development Environment Configuration.

Project Configuration

1.Architectures Settings

Since Xcode 12 provides simulators supporting the arm64 architecture, the framework provided by uni_app supports arm64 for real devices and x86_64 for simulators. So,

Set Excluded Architectures to Any iOS Simulator SDK: arm64.

2.Other Linker Flags

$(inherited) -ObjC -framework "FTMobileSDK" -framework "Guance_UniPlugin_App"

3.Framework Search Paths

$(inherited)
"${PODS_CONFIGURATION_BUILD_DIR}/FTMobileSDK"
"${PODS_CONFIGURATION_BUILD_DIR}/Guance-UniPlugin-App"
$(DEVELOPER_FRAMEWORKS_DIR)
$(PROJECT_DIR)/../SDK/libs
$(PROJECT_DIR)

Using the Main Project UniPlugin-Android for Plugin Development

Project Configuration

For detailed dependency configurations, refer to Demo. More Gradle extension parameter configurations can be found in Android SDK

|-- UniPlugin-Android
    |-- app
        |--build.gradle
        // ---> Configure ft-plugin
        // apply:'ft-plugin'

    |-- uniplugin_module
        |-- src
            |-- main
                |-- java
                    |-- com.ft.sdk.uniapp
        |-- build.gradle 
        //---> Configure dependencies
        //implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-sdk:xxxx'
        //implementation 'com.google.code.gson:gson:xxxx'
        //implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-native:xxxx'

    |-- build.gradle
        //---> Configure repo
        //  maven {
        //          url 'https://mvnrepo.jiagouyun.com/repository/maven-releases'
        //  }
        //
        //--> Configure buildScrpit
        //  classpath 'com.cloudcare.ft.mobile.sdk.tracker.plugin:ft-plugin:xxxx'

Differences Between Android Cloud Packaging and Offline Packaging

Android cloud packaging and offline packaging use two different integration logics. The offline packaging integration method is the same as the Guance Android SDK integration method, using the Android Studio Gradle Plugin way, while cloud packaging cannot use Android Studio Gradle Plugin. Therefore, some functionalities are implemented internally within the Guance UniApp Native Plugin. Hence, the offline packaging version offers more configuration options than the cloud packaging version. The offlinePakcage parameter in the SDK configuration distinguishes between these two cases.

Others

Feedback

Is this page helpful? ×