Skip to content

UniApp Application Integration


Prerequisites

Note: If you have enabled the RUM Headless service, the prerequisites will be automatically configured for you. You can directly integrate your application.

Application Integration

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

Installation

Local Usage

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 sample project
      |-- nativeplugins           // Sample project's local plugin folder
          |-- GCUniPlugin         // ⭐️ GCUniPlugin native plugin package ⭐️
          |   |-- android         // Contains android plugin required libraries and resource files
          |   |-- ios             // Contains ios plugin required libraries and resource files
          |   |-- package.json    // Plugin configuration file
      |-- GCPageMixin.js          // view auto-capture using js, GCPageMixin.js used with GCWatchRouter.js simultaneously
      |-- GCWatchRouter.js        // view auto-capture using js, GCPageMixin.js used with GCWatchRouter.js simultaneously
      |-- GCPageViewMixinOnly.js  // view auto-capture using js, GCPageViewMixinOnly.js used alone
      |-- GCRequest.js            // resource and trace using js, provides APM and network request monitoring capabilities
  |-- UniPlugin-Android           // Plugin development Android main project 
  |-- UniPlugin-iOS               // Plugin development iOS main project 

Place the GCUniPlugin folder under the "nativeplugins" directory of your uni_app project, and also select "Select Local Plugin" under the "App Native Plugin Configuration" item in the manifest.json file, then choose the GCUniPlugin plugin from the list:

img

Note: After saving, you need to submit it for cloud packaging (creating a Custom Base) before the plugin takes effect.

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

Market Plugin Method

(Not provided)

uni Mini Program SDK Installation

Development Debugging and wgt Release Use

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

  • When making the uni mini program SDK into a wgt package for the host App to use, the host App needs to 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 on the left-hand directory, then go to TARGETS -> Build Phases -> Link Binary With Libaries, click the "+" button, and in the pop-up window, click Add Other -> Add Files.... Open the GCUniPlugin/ios/ dependency library directory, select 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,Libraries, and Embedded Content, find FTMobileSDK.xcframework and change the 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: Place ft-native-[version].aar, ft-sdk-[version].aar, gc-uniplugin-[last-version].aar from the GCUniPlugin/android/ folder into the project's libs folder and modify the build.gradle file to add dependencies.

  • Method Two: Use the Gradle Maven remote repository method for configuration. Refer to the UniAndroid-Plugin project configuration here.
  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 above process of adding the GCUniPlugin dependency library, the Native SDK is already added to the host project, so you can directly call Native SDK methods.

  • SDK Initialization

    In mixed usage, only initialize the Native SDK within the host App; there is no need to configure initialization again in the uni mini program. You can directly call the methods provided by the UniApp SDK.

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

    Note: Before loading the uni mini program, ensure that the host App completes the SDK initialization to guarantee that the SDK is fully ready before calling any other SDK methods.

  • Additional Configuration for Android Integration:

    Configure the Gradle Plugin ft-plugin to collect App startup events, network request data, and 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 Local environment deployment (Datakit) reporting URL address, example: http://10.0.0.1:9529, port defaults to 9529, device with SDK installed must be able to access this address. Note: Choose either datakitUrl or datawayUrl
datawayUrl string Yes Public Dataway reporting URL address, obtained from the [Synthetic Tests] application, example: https://open.dataway.url, device with SDK installed must be able to access this address. Note: Choose either datakitUrl or datawayUrl
clientToken string Yes Authentication token, must be used together with datawayUrl
debug boolean No Set whether to allow printing of Debug logs, default false
env string No Environment, default prod, any characters, suggest using single words, such as test etc.
service string No Set the name of the business or service it belongs to. Default: df_rum_ios, df_rum_android
globalContext object No Add 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 collecting data. Default YES. When set to NO, use the flushSyncData method to manage data synchronization manually
syncPageSize number No Set the number of entries per synchronization request. Range [5,). Note: The larger the number of entries, the more computational resources are consumed, default is 10
syncSleepTime number No Set the intermittent synchronization time. Range [0,5000], default not set
enableDataIntegerCompatible boolean No It is recommended to enable when coexisting with web data. This configuration handles web data type storage compatibility issues. Automatically enabled in versions 0.2.1 and later
compressIntakeRequests boolean No Compress uploaded synchronized data using deflate, 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 Set 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 applied during monitoring
iOSAppId string Yes App ID applied 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 turn this off, default is false, unsupported by Android cloud packaging
enableNativeUserResource boolean No Whether to perform automatic tracking of Native Resource, default is false, unsupported by Android cloud packaging. Since uniapp's network requests on iOS use system APIs, enabling this allows all resource data on iOS to be collected together, at which point manual collection on iOS should be disabled to prevent duplicate data collection.
enableNativeUserView boolean No Whether to perform automatic tracking of Native View, pure uni-app applications are recommended to close this, 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 (supported only by 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 the default collection when enableNativeUserResource is set to true. iOS: Supported under >= iOS 13. Android: Okhttp maintains an IP cache mechanism for the same domain, generating only once unless the IP connected to the server changes under the same OkhttpClient.
enableTrackNativeCrash boolean No Whether to collect Native Errors
enableTrackNativeAppANR boolean No Whether to collect Native ANRs
enableTrackNativeFreeze boolean No Whether to collect Native Freezes
nativeFreezeDurationMs number No Set the threshold for collecting Native Freeze stalls, range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms
rumDiscardStrategy string No Discard strategy: discard discards new data (default), discardOldest discards old data
rumCacheLimitCount number No Maximum local cache limit for 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 indicates no collection, 1 indicates full collection, default value is 1.
enableLinkRumData boolean No Whether to associate 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 filtering, array requires filling in log levels: info tips, warning warnings, error errors, critical, ok recovery
globalContext object No Custom global parameters
logCacheLimitCount number No Maximum local cache limit for log entries [1000,), larger logs mean greater disk caching pressure, default 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 indicates no collection, 1 indicates full collection, default value is 1.
traceType string No Trace type: ddTrace (default), zipkinMultiHeader, zipkinSingleHeader, traceparent, skywalking, jaeger
enableLinkRUMData boolean No Whether to associate with RUM data, default false
enableNativeAutoTrace boolean No Whether to enable automatic tracing of native networks iOS NSURLSession, Android OKhttp, default false, unsupported by Android cloud packaging. Since uniapp's network requests on iOS use system APIs, enabling this allows automatic tracing of network requests initiated by iOS uniapp, at which point manual chain tracing on iOS should be disabled to prevent incorrect association of chains 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 Resource, Error, LongTask events. Avoid multiple additions within 0.1 seconds. Only one Action can be associated with the same View at the same time. New Actions added while the previous Action hasn't ended will be discarded. Adding Actions using addAction does not affect each other.

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 Action event. These data cannot be associated with Error, Resource, LongTask data, and there is no 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 set it up in App.vue and the first page the app enters. Refer to the Hbuilder_Example/App.vue, Hbuilder_Example/pages/index/index.vue in the GCUniPlugin plugin example project inside the SDK package.

// step 1. Find GCWatchRouter.js, 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, used separately from GCWatchRouter.js. Refer to the GCUniPlugin plugin example project inside the SDK package Hbuilder_Example/pages/rum/index.vue

//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 page creation duration

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

API - startView

Enter a page

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

API - stopView

Leave a page

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

Error

  • Automatic Collection
/// Use uniapp error listener function triggered when script errors or API call errors occur
<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 message
stack string Yes Stack trace
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 calling method gc.request, inheriting uni.request's 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 on iOS automatically collects network request data initiated through system APIs. To avoid duplicate data collection, you can add the filterPlatform: ["ios"] parameter when using gc.request to block manual data collection on the iOS platform.
  • Manual Collection

Manually implement by calling startResource,stopResource,addResource, refer to the implementation method in 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 a json string
status string Yes Log level
property object No Event context (optional)

Log Levels

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

Tracer Network Chain Trace

  • 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();//Refer to 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 needed for tracing, then add them to the HTTP request headers.

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

Return type: object

User Information Binding and Unbinding

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 additional information

API - unbindRUMUserData

Unbind the current user.

Close SDK

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

API - shutDown

Close the SDK.

Clear 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 Synchronize Data

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

API - flushSyncData

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

When configuring guanceModule.sdkConfig as false, you need to 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 supports only offline packaging and uni mini programs

Add Custom Labels

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 uni-app development tool HBuilderX, download the SDK package required for plugin development.

SDK package structure description

|--iOSSDK   
    |-- HBuilder-Hello              // uni-app offline packaging project
    |-- HBuilder-uniPluginDemo      // uni-app plugin development main project (the project required for this document)
    |-- SDK                         // Dependency libraries and dependent resource files

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

|-- UniPlugin-iOS
    |-- HBuilder-uniPluginDemo      // uni-app plugin development main project (the project required for this document)
    |-- SDK                         // Dependency libraries and dependent 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 real devices, x86_64 simulators. Therefore,

Excluded Architectures set Any iOS Simulator SDK: arm64.

  1. Other Linker Flags
$(inherited) -ObjC -framework "FTMobileSDK" -framework "Guance_UniPlugin_App"
  1. 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

Detailed dependency configurations can be found in the Demo. More Gradle extended 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, cloud packaging cannot use the Android Studio Gradle Plugin, so some functionalities must be implemented internally through Guance UniApp Native Plugin. Therefore, the offline packaging version has more configurable options than the cloud packaging version. The offlinePakcageparameter in the SDK configuration is used to distinguish between these two cases.

Others

Feedback

Is this page helpful? ×