ディープリンクサポートの追加
ディープリンクは、ユーザーをアプリ内の特定のコンテンツに誘導します。アプリがインストールされたデバイスでユーザーがディープリンクをタップすると、アプリは製品ページや特定の体験など、目的のコンテンツに直接開きます。
Singularトラッキングリンクは、標準ディープリンク(インストール済みアプリ用)とディファードディープリンク(新規インストール用)の両方をサポートしています。包括的な情報については、ディープリンクFAQと シンギュラーリンクFAQをご覧ください。
必要条件
前提条件
アプリのディープリンクを有効にするには、Singular Links Prerequisitesを完了してください。
注意事項
- この記事は、Singular Links(Singularのトラッキングリンク技術)を使用していることを前提としています。古いお客様は従来のトラッキングリンクを使用している可能性があります。
- アプリのディープリンク先は、Singularのアプリページで設定する必要があります(アトリビューショントラッキングのためのアプリの設定を参照)。
利用可能なパラメータ
SingularLinkハンドラーは、アプリが開いたときにSingularトラッキングリンクからディープリンク、ディファードディープリンク、パススルーパラメータへのアクセスを提供します。
- ディープリンク (_dl):リンクをクリックしたユーザーのアプリ内のリンク先URL
- ディファードディープリンク(_ddl):リンクをクリックした後にアプリをインストールしたユーザーのリンク先URL
- パススルー(_p):追加コンテキストのためにトラッキングリンクを通して渡されるカスタムデータ
プラットフォーム設定
iOSプラットフォーム設定
iOSのAppDelegateを更新する
AppDelegate ファイルでlaunchOptions とuserActivity オブジェクトを Singular SDK に渡すことで、Singular SDK が起動関連データを処理し、ディープリンクを扱えるようにします。
これらのオブジェクトには、アプリの起動方法と起動理由に関する重要な情報が含まれており、Singularはこれをアトリビューション追跡とディープリンクナビゲーションに使用します。
Objective-Cの実装
// Top of AppDelegate.m
#import "SingularAppDelegate.h"
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
[SingularAppDelegate shared].launchOptions = launchOptions;
return [super application:application
didFinishLaunchingWithOptions:launchOptions];
}
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>>
*restorableObjects))restorationHandler {
[[SingularAppDelegate shared] continueUserActivity:userActivity
restorationHandler:restorationHandler];
return [super application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
[[SingularAppDelegate shared] handleOpenUrl:url options:options];
return [super application:app openURL:url options:options];
}
Swiftの実装
import singular_flutter_sdk
override func application(_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self)
if let singularAppDelegate = SingularAppDelegate.shared() {
singularAppDelegate.launchOptions = launchOptions
}
return super.application(application,
didFinishLaunchingWithOptions:launchOptions)
}
override func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
if let singularAppDelegate = SingularAppDelegate.shared() {
singularAppDelegate.continueUserActivity(userActivity,
restorationHandler: nil)
}
return super.application(application,
continue: userActivity,
restorationHandler: restorationHandler)
}
override func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if let singularAppDelegate = SingularAppDelegate.shared() {
singularAppDelegate.handleOpen(url, options: options)
}
return super.application(app, open: url, options: options)
}
Android プラットフォームの設定
AndroidのMainActivityを更新する
Intent オブジェクトを Singular SDK に渡すようにMainActivity ファイルを修正することで、Singular SDK が起動関連データを処理し、ディープリンクを処理できるようにします。
Intent オブジェクトには、アプリの起動方法と起動理由に関する情報が含まれており、Singular はこれをアトリビューション追跡とディープリンクナビゲーションに使用します。
Javaの実装
// Add as part of the imports at the top of the class
import android.content.Intent;
import com.singular.flutter_sdk.SingularBridge;
// Add to the MainActivity class
@Override
public void onNewIntent(Intent intent) {
if(intent.getData() != null) {
setIntent(intent);
super.onNewIntent(intent);
SingularBridge.onNewIntent(intent);
}
}
Kotlinの実装
// Add as part of the imports at the top of the class
import android.content.Intent
import com.singular.flutter_sdk.SingularBridge
// Add to the MainActivity class
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.data != null) {
setIntent(intent)
SingularBridge.onNewIntent(intent)
}
}
SDKの設定
Singular Linksハンドラの実装
SDK 初期化中にsingularLinksHandler コールバックを設定し、受信ディープリンクと遅延ディープリンクデータを処理します。
import 'package:flutter/material.dart';
import 'package:singular_flutter_sdk/singular.dart';
import 'package:singular_flutter_sdk/singular_config.dart';
import 'package:singular_flutter_sdk/singular_link_params.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
initializeSDK();
}
void initializeSDK() {
// Create SDK configuration
SingularConfig config = SingularConfig(
'YOUR_SDK_KEY',
'YOUR_SDK_SECRET'
);
// Configure deep link handler
config.singularLinksHandler = (SingularLinkParams params) {
print('=== Singular Link Resolved ===');
print('Deep link: ${params.deeplink}');
print('Passthrough: ${params.passthrough}');
print('Is deferred: ${params.isDeferred}');
// Handle deep link navigation
if (params.deeplink != null) {
handleDeepLink(params.deeplink!, params.isDeferred);
}
// Handle passthrough data
if (params.passthrough != null) {
handlePassthroughData(params.passthrough!);
}
};
// Initialize SDK
Singular.start(config);
}
void handleDeepLink(String url, bool isDeferred) {
print('Routing to: $url (Deferred: $isDeferred)');
// Parse URL and navigate to appropriate screen
// Example: myapp://product/123
if (url.contains('product')) {
final productId = url.split('/').last;
navigateToProduct(productId);
} else if (url.contains('promo')) {
navigateToPromo(url);
}
}
void handlePassthroughData(String passthrough) {
print('Processing passthrough data: $passthrough');
// Parse and use passthrough data as needed
}
void navigateToProduct(String productId) {
// Your navigation logic
print('Navigating to product: $productId');
}
void navigateToPromo(String url) {
// Your navigation logic
print('Navigating to promo: $url');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
設定プロパティ:
void Function(SingularLinkParams)? singularLinksHandler
注意: singularLinksHandler コールバックは、アプリが Singular Links を介して開いた場合にのみトリガーされます。詳細については、Singular Links FAQを参照してください。
完全なドキュメントはsingularLinksHandler リファレンスを参照してください。
ハンドラの動作
リンク解決を理解する
singularLinksHandler は、アプリがインストールされたばかりか、既にインストールされているかによって動作が異なります。
新規インストール (ディープリンクの遅延)
新規インストールでは、アプリの起動時に Open URL は存在しません。トラッキングリンクにディープリンクまたはディファードディープリンクの値が含まれているかどうかを判断するために、アトリビューションが完了します。
ディファードディープリンクのフロー
- ユーザーがディープリンク値で設定されたSingularトラッキングリンクをクリックする。
- ユーザーがアプリをインストールして初めて開く
- Singular SDKが最初のセッションをSingularサーバーに送信します。
- アトリビューションが完了し、トラッキングリンクからディープリンクが特定される
- ディープリンクの値が
deeplinkパラメータのisDeferred = trueでsingularLinksHandlerコールバックに返される
ディファードディープリンクのテスト
- テストデバイスからアプリをアンインストールする(現在インストールされている場合)
- iOS:IDFA をリセットします。Android: IDFAをリセットします:Google Advertising ID (GAID)をリセットする。
- デバイスからSingularトラッキングリンクをクリックする(ディープリンク値が設定されていることを確認する)
- アプリをインストールして開く
アトリビューションが正常に完了し、延期されたディープリンク値がsingularLinksHandler ハンドラーに渡されます。
プロのヒント異なるパッケージ名(例えば、com.example.prod の代わりにcom.example.dev )を使用する開発ビルドでディープリンクをテストする場合、開発アプリのパッケージ名専用にトラッキングリンクを設定してください。テストリンクをクリックした後、アプリストアから本番アプリをダウンロードするのではなく、開発ビルドをデバイスに直接インストールしてください(Android Studio または Xcode 経由)。
インストール済み(即時ディープリンク)
アプリが既にインストールされている場合、ユニバーサルリンク(iOS)またはAndroid App Linksテクノロジーを使用して、シングラーリンクをクリックするとアプリが即座に開きます。
即時ディープリンクフロー:
- ユーザーがSingularトラッキングリンクをクリック
- オペレーティングシステムは、Singularトラッキングリンク全体を含むOpen URLを提供します。
- SDKの初期化中にSingularがURLを解析します。
- Singularは
deeplinkとpassthroughの値を抽出します。 - 値は
isDeferred = falseとともにsingularLinksHandlerハンドラーを通して返されます。
高度な機能
パススルーパラメータ
パススルーパラメーターを使用して、トラッキングリンククリックから追加データを取得します。
passthrough (_p) パラメーターがトラッキングリンクに含まれている場合、singularLinksHandler ハンドラーのpassthrough パラメーターに対応するデータが含まれます。キャンペーンメタデータ、ユーザーセグメンテーションデータ、またはアプリで必要なカスタム情報を取得するために使用します。
import 'package:singular_flutter_sdk/singular_config.dart';
import 'package:singular_flutter_sdk/singular_link_params.dart';
import 'dart:convert';
SingularConfig config = SingularConfig('API_KEY', 'SECRET');
config.singularLinksHandler = (SingularLinkParams params) {
// Extract passthrough data
final passthroughData = params.passthrough;
if (passthroughData != null) {
try {
// Parse JSON passthrough data
final jsonData = jsonDecode(passthroughData);
print('Campaign ID: ${jsonData['campaign_id']}');
print('User Segment: ${jsonData['segment']}');
print('Promo Code: ${jsonData['promo_code']}');
// Apply campaign-specific settings
applyCampaignSettings(jsonData);
} catch (error) {
print('Error parsing passthrough data: $error');
}
}
};
void applyCampaignSettings(Map<String, dynamic> data) {
// Your campaign logic here
print('Applying campaign settings: $data');
}
すべてのクエリパラメータを転送する
_forward_params=2 パラメータをトラッキングリンクに追加することで、トラッキングリンクURLからすべてのクエリパラメータを取得します。
_forward_params=2 をトラッキングリンクに追加すると、すべてのクエリパラメータがsingularLinksHandler ハンドラのdeeplink パラメータに含まれ、すべてのパラメータを含む完全な URL にアクセスできるようになります。
トラッキングリンクの例https://yourapp.sng.link/A1b2c/abc123?_dl=myapp://product/123&_forward_params=2&utm_source=facebook&promo=SALE2024
singularLinksHandler ハンドラーが受信します:deeplink = "myapp://product/123?utm_source=facebook&promo=SALE2024"
完全な実装例
ナビゲーション、パススルー処理、Flutterアプリのパラメータ転送を含む包括的なディープリンク実装。
import 'package:flutter/material.dart';
import 'package:singular_flutter_sdk/singular.dart';
import 'package:singular_flutter_sdk/singular_config.dart';
import 'package:singular_flutter_sdk/singular_link_params.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
@override
void initState() {
super.initState();
initializeSDK();
}
void initializeSDK() {
SingularConfig config = SingularConfig(
'YOUR_SDK_KEY',
'YOUR_SDK_SECRET'
);
config.singularLinksHandler = (SingularLinkParams params) {
print('=== Singular Link Resolved ===');
print('Deep link: ${params.deeplink}');
print('Passthrough: ${params.passthrough}');
print('Is deferred: ${params.isDeferred}');
// Handle passthrough data
if (params.passthrough != null) {
handlePassthroughData(params.passthrough!);
}
// Handle deep link navigation
if (params.deeplink != null) {
handleDeepLinkNavigation(params.deeplink!, params.isDeferred);
}
};
Singular.start(config);
}
void handlePassthroughData(String passthroughString) {
try {
final data = jsonDecode(passthroughString);
// Apply promo code if present
if (data.containsKey('promo_code')) {
applyPromoCode(data['promo_code']);
}
// Set user segment
if (data.containsKey('segment')) {
setUserSegment(data['segment']);
}
// Track campaign
if (data.containsKey('campaign_id')) {
trackCampaign(data['campaign_id']);
}
} catch (error) {
print('Error parsing passthrough: $error');
}
}
void handleDeepLinkNavigation(String url, bool isDeferred) {
// Parse URL to extract route and parameters
final urlObj = parseDeepLink(url);
print('Navigating to: ${urlObj['route']}');
print('Parameters: ${urlObj['params']}');
print('Deferred install: $isDeferred');
// Route based on deep link structure
switch (urlObj['route']) {
case 'product':
navigateToProduct(urlObj['params']['id']);
break;
case 'promo':
navigateToPromo(urlObj['params']['code']);
break;
case 'category':
navigateToCategory(urlObj['params']['name']);
break;
default:
navigateToHome();
}
}
Map<String, dynamic> parseDeepLink(String url) {
// Parse myapp://product/123?variant=blue
final parts = url.split('?');
final path = parts[0];
final queryString = parts.length > 1 ? parts[1] : null;
// Extract path components
final pathParts = path.replaceFirst(RegExp(r'^[^:]+://'), '').split('/');
final route = pathParts[0];
// Parse parameters
final params = <String, String>{};
// Add path parameters
if (pathParts.length > 1) {
params['id'] = pathParts[1];
}
// Add query parameters
if (queryString != null) {
queryString.split('&').forEach((pair) {
final keyValue = pair.split('=');
if (keyValue.length == 2) {
params[keyValue[0]] = Uri.decodeComponent(keyValue[1]);
}
});
}
return {
'route': route,
'params': params
};
}
// Navigation functions
void navigateToProduct(String? productId) {
if (productId != null) {
print('Navigating to product: $productId');
// Use your navigation framework (Navigator, GoRouter, etc.)
navigatorKey.currentState?.pushNamed('/product/$productId');
}
}
void navigateToPromo(String? promoCode) {
if (promoCode != null) {
print('Navigating to promo: $promoCode');
navigatorKey.currentState?.pushNamed('/promo/$promoCode');
}
}
void navigateToCategory(String? categoryName) {
if (categoryName != null) {
print('Navigating to category: $categoryName');
navigatorKey.currentState?.pushNamed('/category/$categoryName');
}
}
void navigateToHome() {
print('Navigating to home');
navigatorKey.currentState?.pushNamed('/');
}
// Utility functions
void applyPromoCode(String code) {
print('Applying promo code: $code');
// Your promo code logic
}
void setUserSegment(String segment) {
print('Setting user segment: $segment');
// Your user segmentation logic
}
void trackCampaign(String campaignId) {
print('Tracking campaign: $campaignId');
// Your campaign tracking logic
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
navigatorKey: navigatorKey,
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/product': (context) => ProductScreen(),
'/promo': (context) => PromoScreen(),
'/category': (context) => CategoryScreen(),
},
);
}
}
// Placeholder screen classes
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: Center(child: Text('Home Screen')),
);
}
}
class ProductScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product')),
body: Center(child: Text('Product Screen')),
);
}
}
class PromoScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Promo')),
body: Center(child: Text('Promo Screen')),
);
}
}
class CategoryScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Category')),
body: Center(child: Text('Category Screen')),
);
}
}
ベストプラクティス:
- URLを安全に解析する:セキュリティの脆弱性を防ぐために、ナビゲーションの前に常にディープリンクのURLを検証し、サニタイズする。
- Navigation Stateを扱う:NavigatorStateにGlobalKeyを使い、MaterialAppが完全に初期化される前にナビゲーションを有効にする。
- 両方のシナリオをテストする:開発中に、即時ディープリンク(アプリをインストール)と遅延ディープリンク(新規インストール)の両方をテストする。
- デバッグのためのログ:開発中に包括的なロギングを有効にして、ディープリンクの解決とナビゲーションのフローをトレースします。
- エラー処理:JSON解析とナビゲーション操作にtry-catchブロックを実装し、不正なデータを優雅に処理する。