React Native SDK - SDK 方法参考

文档

React Native SDK 方法参考

本综合参考文档记录了用于移动应用程序跟踪的 Singular SDK 中的所有可用方法。SDK 提供了初始化、用户识别、事件跟踪、收入报告、归因、数据隐私合规性和配置等功能。每种方法都附有说明、签名和实际使用示例,以帮助开发人员将 Singular SDK 功能集成到自己的应用程序中。


adRevenue

Singular.adRevenue Method

通过详细的广告数据信息跟踪广告收入事件。

签名

static adRevenue(adData: SingularAdData): void

使用示例

typescript
// Create ad data object 
const adData = new SingularAdData()
     .withAdPlatform("AdMob")
     .withAdType("Rewarded")
     .withAdNetworkName("Google")
     .withCurrency("USD")
     .withRevenue(0.05);

// Track ad revenue event
Singular.adRevenue(adData);

clearGlobalProperties

Singular.clearGlobalProperties Method

删除之前设置的所有全局属性。

签名

static clearGlobalProperties(): void

使用示例

typescript
// Clear all global properties, for example when a user logs out 
Singular.clearGlobalProperties();

createReferrerShortLink

Singular.createReferrerShortLink Method

创建带有推荐人信息的简短链接,可用于分享和归属。

签名

static createReferrerShortLink(baseLink: string, referrerName: string, referrerId: string, passthroughParams: SerializableObject, completionHandler: (result: string, error: string) => void): void

使用示例

typescript
Singular.createReferrerShortLink( 
        "https://sample.sng.link/B4tbm/v8fp?_dl=https%3A%2F%2Fabc.com", 
        "John Doe", // Referrer Name 
        "aq239897", // Referrer ID 
        { "channel": "sms", "campaign": "summer_promo" }, // Passthrough parameters 
        (shortLinkURL, error) => { if (error) { 
           console.error("Error creating short link:", error); return; }
           console.log("Generated short link:", shortLinkURL);
          // Share the link with users
     }
);

customRevenue

Singular.customRevenue Method

使用指定的事件名称、货币和金额跟踪自定义收入事件。

  • 自定义收入事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后限制为 32 字节。
  • 货币代码必须是大写字母,并符合三个字母的ISO 4217货币代码

签名

static customRevenue(eventName: string, currency: string, amount: number): void

使用示例

typescript
// Track a custom revenue event 
Singular.customRevenue("premium_subscription", "USD", 9.99);

customRevenueWithArgs

Singular.customRevenueWithArgs Method

使用指定的事件名称、货币、金额和其他自定义属性跟踪自定义收入事件。

  • 自定义收入事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后限制为 32 字节。
  • 事件属性名称和属性值限制为 500 个 ASCII 字符。
  • 货币代码必须使用大写字母,并符合三个字母的ISO 4217货币代码

签名

static customRevenueWithArgs(eventName: string, currency: string, amount: number, args: SerializableObject): void

使用示例

typescript
// Track a custom revenue event with additional parameters 
Singular.customRevenueWithArgs( 
        "in_app_purchase", 
        "USD", 
        5.99, 
        { 
           "product_id": "com.app.gems_pack_small", 
           "quantity": 1, 
           "transaction_id": "T12345678", 
           "receipt_id": "R98765432" 
        }
);

event

Singular.event Method

使用 Singular 的 SDK 跟踪一个简单的自定义事件。

  • 事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后限制为 32 字节。

签名

static event(eventName: string): void

使用示例

typescript
// Track a simple event 
Singular.event("level_completed");

eventWithArgs

Singular.eventWithArgs Method

使用 Singular 的 SDK 跟踪带有附加属性的自定义事件。

  • 事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后,限制为 32 字节。
  • 事件属性名称和属性值限制为 500 个 ASCII 字符。

签名

static eventWithArgs(eventName: string, args: SerializableObject): void

使用示例

typescript
// Track an event with additional parameters 
Singular.eventWithArgs(
        "level_completed", 
        { 
           "level_number": 5, 
           "difficulty": "hard", 
           "time_spent": 120, 
           "score": 9500 
        }
);

getLimitDataSharing

Singular.getLimitDataSharing Method

获取用户当前的数据共享限制状态。

签名

static getLimitDataSharing(): boolean

使用示例

typescript
// Check if data sharing is limited 
const isLimited = Singular.getLimitDataSharing(); 
console.log("Data sharing limitation status:", isLimited);

// Use the status to adjust app behavior
if (isLimited) {
     // Adjust functionality for users with limited data sharing
}

getGlobalProperties

Singular.getGlobalProperties Method

读取当前设置的所有全局属性。

签名

static getGlobalProperties(): Map<string, string>

使用示例

typescript
// Get all global properties 
const properties = Singular.getGlobalProperties();
        
     // Iterate through properties
     properties.forEach((value, key) => {
        console.log(${key}: ${value});
     });

inAppPurchase

Singular.inAppPurchase Method

此方法需要使用React Native 的应用内购买软件包管理应用程序中的交易。

跟踪带有购买详细信息的应用内购买事件。

  • 事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后限制为 32 字节。

签名

static inAppPurchase(eventName: string, purchase: SingularPurchase): void

使用示例

typescript
// Add the Singular Purchase Class imports
import { 
        Singular, 
        SingularConfig, 
        Events, 
        SingularPurchase, 
        SingularIOSPurchase, 
        SingularAndroidPurchase } from 'singular-react-native';
  
// Create purchase object
let singularPurchase = null;
  
if (Platform.OS === 'ios') {
   singularPurchase = new SingularIOSPurchase(
     product.revenue,
     product.currency,
     purchase.productId,
     purchase.transactionId,
     purchase.transactionReceipt,
   );
  } else if (Platform.OS === 'android'){
   singularPurchase = new SingularAndroidPurchase(
     product.revenue,
     product.currency,
     purchase.transactionReceipt,
     purchase.signatureAndroid,
   );
}
  
// Track in-app purchase
Singular.inAppPurchase('iap_purchase', singularPurchase);

inAppPurchaseWithArgs

Singular.inAppPurchaseWithArgs Method

此方法需要使用React Native 的应用内购买软件包管理应用程序中的交易。

跟踪带有购买详细信息和其他自定义属性的应用内购买事件。

  • 事件名称限制为 32 个 ASCII 字符。对于非 ASCII 字符,转换为 UTF-8 后限制为 32 字节。
  • 事件属性名称和属性值限制为 500 ASCII 字符。

签名

static inAppPurchaseWithArgs(eventName: string, purchase: SingularPurchase, args: SerializableObject): void

使用示例

typescript
// Add the Singular Purchase Class imports
import { 
        Singular, 
        SingularConfig, 
        Events, 
        SingularPurchase, 
        SingularIOSPurchase, 
        SingularAndroidPurchase } from 'singular-react-native';
  
// Create purchase object
let singularPurchase = null;
  
if (Platform.OS === 'ios') {
   singularPurchase = new SingularIOSPurchase(
     product.revenue,
     product.currency,
     purchase.productId,
     purchase.transactionId,
     purchase.transactionReceipt,
   );
  } else if (Platform.OS === 'android'){
   singularPurchase = new SingularAndroidPurchase(
     product.revenue,
     product.currency,
     purchase.transactionReceipt,
     purchase.signatureAndroid,
   );
}
        
// Track in-app purchase with additional attributes
Singular.inAppPurchaseWithArgs(
     "iap_purchase",
     singularPurchase,
     {
        "is_first_purchase": true,
        "subscription_type": "yearly",
        "discount_applied": "holiday_special",
        "previous_subscription": "monthly"
     }
);

init

Singular.init Method

使用提供的配置初始化 Singular SDK。config 参数是SingularConfig 对象,必须使用构造函数用有效的SDK Key (apiKey)Secret (secret) 将其实例化:new SingularConfig(apikey: string, secret: string)

签名

static init(config: SingularConfig): void

使用示例

typescript
// Create configuration 
const config = new SingularConfig('SDK KEY', 'SDK SECRET')
     .withCustomUserId("user123")
     .withSessionTimeoutInSec(60)
     .withLimitDataSharing(false)
     .withSingularLink((params) => { 
        // Handle deep link parameters 
        console.log("Deep link received:", params); 
     });

// Initialize Singular SDK
Singular.init(config);

isAllTrackingStopped

Singular.isAllTrackingStopped Method

检查 SDK 是否已停止所有跟踪。

签名

static isAllTrackingStopped(): boolean

使用示例

typescript
// Check if tracking is currently stopped 
const isTrackingStopped = Singular.isAllTrackingStopped();
        
     // Adjust UI based on tracking status
     if (isTrackingStopped) {
        console.log("All tracking is currently stopped");
        // Update UI to reflect tracking status
     } else {
        console.log("Tracking is active");
     }

limitDataSharing

Singular.limitDataSharing Method

限制当前用户的数据共享,通常用于遵守 CCPA。

签名

static limitDataSharing(shouldLimitDataSharing: boolean): void

使用示例

typescript
// To limit data sharing (e.g., when user opts out) 
Singular.limitDataSharing(true);
        
// To enable full data sharing (e.g., when user opts in)
Singular.limitDataSharing(false);

resumeAllTracking

Singular.resumeAllTracking Method

恢复已停止的所有跟踪活动。

签名

static resumeAllTracking(): void

使用示例

typescript
// Resume tracking when user opts back in 
Singular.resumeAllTracking();
console.log("Tracking has been resumed");
// Update UI to reflect that tracking is now active

revenue

Singular.revenue Method

使用指定的货币和金额跟踪简单的收入事件。

  • 货币代码必须是大写字母,并符合三个字母的ISO 4217货币代码

签名

static revenue(currency: string, amount: number): void

使用示例

typescript
// Track a simple revenue event 
Singular.revenue("USD", 19.99);

revenueWithArgs

Singular.revenueWithArgs Method

跟踪带有指定货币、金额和附加自定义属性的收入事件。

  • 事件属性名称和属性值限制为 500 个 ASCII 字符。
  • 货币代码必须使用大写字母,并遵守三个字母的ISO 4217货币代码

签名

static revenueWithArgs(currency: string, amount: number, args: SerializableObject): void

使用示例

typescript
// Track a revenue event with additional parameters 
Singular.revenueWithArgs(
     "EUR", 
     9.99, 
     { 
        "subscription_type": "monthly", 
        "is_promotional": false, 
        "user_tier": "premium", 
        "payment_method": "credit_card" 
     }
);

setCustomUserId

Singular.setCustomUserId Method

为当前用户设置自定义用户 ID,供 Singular SDK 使用。

签名

static setCustomUserId(customUserId: string): void

使用示例

typescript
// Set the custom user ID after user logs in 
Singular.setCustomUserId("user_123456");

setDeviceCustomUserId

Singular.setDeviceCustomUserId Method

企业功能:将自定义用户 ID 与当前设备关联,用于跨平台跟踪。

签名

static setDeviceCustomUserId(customUserId: string): void

使用示例

typescript
// Set a device-level custom user ID 
Singular.setDeviceCustomUserId("device_user_987654");

setGlobalProperty

Singular.setGlobalProperty Method

设置全局属性,该属性将与所有后续事件一起发送。

签名

static setGlobalProperty(key: string, value: string, overrideExisting: boolean): boolean

使用示例

typescript
// Set a global property that will be included with all events 
const wasSet = Singular.setGlobalProperty("user_tier", "premium", true);
        
// Set another global property without overriding if it exists
Singular.setGlobalProperty("app_version", "2.1.3", false);
        
if (wasSet) {
     console.log("Global property was set successfully");
}

setUninstallToken

Singular.setUninstallToken Method

设置设备令牌,以便通过推送通知进行卸载跟踪。

签名

static setUninstallToken(token: string): void

使用示例

typescript
// Set the device token for uninstall tracking 
// This is typically obtained from the platform's push notification service 
const deviceToken = "a1b2c3d4e5f6g7h8i9j0..."; // FCM or APNS token 
Singular.setUninstallToken(deviceToken);

skanGetConversionValue

Singular.skanGetConversionValue Method

获取当前 SKAdNetwork 转换值(仅限 iOS)。

签名

static skanGetConversionValue(): number | null

使用示例

typescript
// Get the current SKAdNetwork conversion value 
const conversionValue = Singular.skanGetConversionValue();
        
if (conversionValue !== null) {
     console.log("Current conversion value:", conversionValue);
} else {
     console.log("Conversion value not available");
}

skanRegisterAppForAdNetworkAttribution

Singular.skanRegisterAppForAdNetworkAttribution Method

将应用程序注册为 SKAdNetwork 归属(仅限 iOS)。

签名

static skanRegisterAppForAdNetworkAttribution(): void

使用示例

typescript
// Register app for SKAdNetwork attribution 
// This is typically called early in the app lifecycle 
Singular.skanRegisterAppForAdNetworkAttribution();

skanUpdateConversionValue

Singular.skanUpdateConversionValue Method

更新 SKAdNetwork 转换值(仅限 iOS)。

签名

static skanUpdateConversionValue(conversionValue: number): boolean

使用示例

typescript
// Update the SKAdNetwork conversion value 
// Value must be between 0-63 
const wasUpdated = Singular.skanUpdateConversionValue(12);

     if (wasUpdated) {
        console.log("Conversion value was updated successfully");
     } else {
        console.log("Failed to update conversion value");
     }

skanUpdateConversionValues

Singular.skanUpdateConversionValues Method

更新 SKAdNetwork 4.0 转换值,包括精细、粗糙和锁定窗口(仅限 iOS 16.1+)。

签名

static skanUpdateConversionValues(conversionValue: number, coarse: number, lock: boolean): void

使用示例

typescript
// Update SKAdNetwork 4.0 conversion values 
// Fine value: 0-63 
// Coarse value: 0-2 (Low, Medium, High) 
// Lock: whether to lock the postback window 
Singular.skanUpdateConversionValues(45, 2, false);
        
// Example with named constants for clarity
const FINE_VALUE = 45;
const COARSE_VALUE_HIGH = 2;
const LOCK_WINDOW = false;
Singular.skanUpdateConversionValues(FINE_VALUE, COARSE_VALUE_HIGH, LOCK_WINDOW);

stopAllTracking

Singular.stopAllTracking Method

停止 SDK 中的所有跟踪活动。

签名

static stopAllTracking(): void

使用示例

typescript
// Stop all tracking when user opts out 
Singular.stopAllTracking();
console.log("All tracking has been stopped");
// Update UI to reflect that tracking is now disabled

trackingOptIn

Singular.trackingOptIn Method

出于分析和归因目的,选择对用户进行跟踪。

签名

static trackingOptIn(): void

使用示例

typescript
// Call when user has consented to tracking 
Singular.trackingOptIn();
console.log("User has opted into tracking");

trackingUnder13

Singular.trackingUnder13 Method

将用户标记为 13 岁以下,根据 COPPA 限制数据收集。

签名

static trackingUnder13(): void

使用示例

typescript
// If user is determined to be under 13 years old 
Singular.trackingUnder13();
console.log("User marked as under 13, GDPR_UNDER_13 flag applied");

unsetCustomUserId

Singular.unsetCustomUserId Method

从 Singular 跟踪中删除之前设置的自定义用户 ID。

签名

static unsetCustomUserId(): void

使用示例

typescript
// Remove the custom user ID when user logs out 
Singular.unsetCustomUserId();
console.log("Custom user ID has been removed");

unsetGlobalProperty

Singular.unsetGlobalProperty Method

删除先前设置的全局属性。

签名

static unsetGlobalProperty(key: string): void

使用示例

typescript
// Remove a global property that is no longer needed 
Singular.unsetGlobalProperty("temporary_campaign_id");
console.log("Global property has been removed");