将 Campaign SDK 与您的应用程序集成 integrate-campaign-sdk

您可以使用适用于iOS和Android的Campaign SDK,促进将移动应用程序集成到Adobe Campaign平台。

兼容性矩阵中列出了Android和iOS支持的版本,以及Campaign v8的Campaign SDK兼容版本。

作为Campaign管理员,您可以从Experience Cloud软件分发下载Campaign SDK。 有关详细信息,请联系Adobe客户关怀

NOTE
您还可以通过在数据收集UI中配置Adobe Experience Platform扩展来使用Adobe Campaign Mobile SDK。 在开发人员文档中了解详情

声明集成设置 declaring-integration-settings

要将Campaign SDK集成到移动应用程序,功能管理员必须向开发人员提供以下信息:

  • 集成键:用于启用Adobe Campaign平台以识别移动应用程序。

    note note
    NOTE
    此集成密钥输入到Adobe Campaign控制台中,该控制台位于专用于移动应用程序的服务的​ Information ​选项卡中。
  • 跟踪URL:与Adobe Campaign跟踪服务器的地址匹配。

  • 营销URL:启用订阅集合。

  • 在Android

    code language-sql
    Neolane.getInstance().setIntegrationKey("your Adobe mobile app integration key");
    Neolane.getInstance().setMarketingHost("https://yourMarketingHost:yourMarketingPort/");
    Neolane.getInstance().setTrackingHost("https://yourTrackingHost:yourTrackingPort/");
    
  • 在iOS

    code language-sql
    Neolane_SDK *nl = [Neolane_SDK getInstance];
    [nl setMarketingHost:strMktHost];
    [nl setTrackingHost:strTckHost];
    [nl setIntegrationKey:strIntegrationKey];
    

集成Android SDK

Android SDK是使用JAVA编写的jar库。 它允许Android开发人员与Adobe Campaign集成:注册新设备、将设备与用户关联、跟踪行为等。

在此部分中,了解如何在实现Android Firebase Cloud Messaging (FCM)的Android应用程序中使用Google SDK。

CAUTION
对于Campaign v8,请使用Campaign Android SDK v1.1.1。

配置FCM

要在Android上使用推送通知,您必须拥有FCM帐户,配置Android应用程序以接收通知,并将应用程序链接到FCM帐户。 请参阅Google文档以了解详情。

请参阅Google文档以将Firebase添加到您的Android项目。

请参阅Google文档以了解如何在应用程序中实施FCM。

NOTE
  • 不要忘记下载并将google-services.json添加到您的项目中。

  • apiKey必须与在链接到此Android应用程序的Adobe Campaign Mobile应用程序中设置的projectKey匹配。

配置Android SDK

  1. 初始化SDK

    在使用Android SDK之前,您需要对其进行初始化。 SDK初始化可以在活动的onCreate函数中完成。

    code language-sql
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    
        // initialize Campaign SDK
        SharedPreferences settings = getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
    
        Neolane.getInstance().setIntegrationKey(settings.getString(YourApplicationActivity.APPUUID_NAME, YourApplicationActivity.DFT_APPUUID));
        Neolane.getInstance().setMarketingHost(settings.getString(YourApplicationActivity.SOAPRT_NAME, YourApplicationActivity.DFT_SOAPRT));
        Neolane.getInstance().setTrackingHost(settings.getString(YourApplicationActivity.TRACKRT_NAME, YourApplicationActivity.DFT_TRACKRT));
        ...
    }
    

    IntegrationKey必须与在链接到此Android应用程序的Adobe Campaign移动设备应用程序中设置的“IntegrationKey”匹配。

  2. 将移动设备注册到Adobe Campaign服务器

    注册功能使您能够:

    • 将通知ID或推送ID(iOS的deviceToken和Android的注册ID)发送到Adobe Campaign。
    • 恢复协调密钥或userKey(例如,电子邮件或帐号)

    您必须在应用程序初始化或用户操作时,将设备注册到Adobe Campaign。 可以使用registerDevice方法轻松完成此操作。

    code language-sql
    public void onClick(View v)
    {
    SharedPreferences settings = this.context.getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
    EditText mailEdit = (EditText) this.context.findViewById(R.id.editText1);
    
    final String FCMRegistrationId = FirebaseInstanceId.getInstance().getToken();
    if (FCMRegistrationId != null)
        NeoTripActivity.registerOnNeolane(this.context, FCMRegistrationId, mailEdit.getText().toString());
    
    }
    

    YourApplicationActivity.java

    code language-sql
    public static void registerOnNeolane(final Context ctx, String registrationId, String userKey)
    {
        NeolaneAsyncRunner neolaneAs = new NeolaneAsyncRunner(Neolane.getInstance());
        // Additional Subscription Parameters
        Map<String,Object> additionnalParam = new HashMap<String, Object>();
        additionnalParam.clear();
        SharedPreferences settings = ctx.getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
        if (settings.getBoolean(YourApplicationActivity.SUBPARAMEN1_NAME, false))
        {
            additionnalParam.put(settings.getString(YourApplicationActivity.SUBPARAMNAME1_NAME, "") , settings.getString(YourApplicationActivity.SUBPARAMVALUE1_NAME, ""));
        }
        if (settings.getBoolean(YourApplicationActivity.SUBPARAMEN2_NAME, false))
        {
            additionnalParam.put(settings.getString(YourApplicationActivity.SUBPARAMNAME2_NAME, "") , settings.getString(YourApplicationActivity.SUBPARAMVALUE2_NAME, ""));
        }
        if ( additionnalParam.isEmpty() )
        {
            additionnalParam = null;
        }
        // Campaign Registration
        neolaneAs.registerDevice(registrationId, userKey, additionnalParam, ctx, new RequestListener() {
        public void onComplete(String e, Object obj)
        {
            Intent upd = new Intent();
            upd.setAction(BROADCAST_NEWREGISTER_ACTION);
            ctx.sendBroadcast(upd);
        }
    
        public void onNeolaneException(NeolaneException e, Object obj)
        {
            sendErrorMsg(e.getErrorString());
        }
    
        public void onIOException(IOException e, Object obj)
        {
            sendErrorMsg(e.getMessage());
        }
    
        public void sendErrorMsg(String err)
        {
            SharedPreferences.Editor edit = ctx.getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE).edit();
            edit.putBoolean(YourApplicationActivity.REGISTRATION_ERROR_NEOLANE_KEYNAME, true);
            edit.commit();
            Intent toast = new Intent();
            toast.setAction(BROADCAST_TOAST_DISPLAY_TEXT);
            toast.putExtra("text", "An error happened, please register again (" + err + ")");
            ctx.sendBroadcast(toast);
        }
        });
    }
    
  3. 当用户的移动设备令牌更改时通知Campaign

    我们建议您在调用onTokenRefresh函数时使用registerDevice函数来通知Adobe Campaign用户的移动设备令牌发生了更改。

    例如:

    YourApplicationFirebaseInstanceIDService.java

    code language-sql
    package com.android.YourApplication;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.util.Log;
    
    import com.google.firebase.iid.FirebaseInstanceId;
    import com.google.firebase.iid.FirebaseInstanceIdService;
    
    import static android.content.SharedPreferences.*;
    
    public class YourApplicationFirebaseInstanceIDService extends FirebaseInstanceIdService
    {
        @Override
        public void onTokenRefresh()
        {
        SharedPreferences settings = getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
        if (!settings.getBoolean(YourApplicationActivity.USE_GCM, false))
            {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            String userKey = settings.getString(YourApplicationActivity.USERKEY_NAME, "");
            Editor edit = settings.edit();
            edit.putString(YourApplicationActivity.FCM_REGISTRATIONID_NAME, refreshedToken);
            edit.commit();
            YourApplicationActivity.registerOnNeolane(this, refreshedToken, userKey);
            }
        }
    }
    
  4. 配置Firebase消息服务

    扩展onMessageReceived回调中的FirebaseMessagingService以接收消息。 我们建议您在调用onMessageReceived回调时调用notifyReceive函数以启用对移动设备上通知接收的跟踪。 在Adobe Campaign中,此名称为​ print ​通知:在请求OS显示通知之前,应调用此函数。

    YourApplicationMessagingService.java

    code language-sql
    package com.android.YourApplication;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    
    public class YourApplicationFirebaseMessagingService extends FirebaseMessagingService
        {
        private static final String TAG = "MyFirebaseMsgService";
    
        @Override
        public void onMessageReceived(RemoteMessage message)
            {
            Log.d(TAG, "Receive message from: " + message.getFrom());
            Map<String,String> payloadData = message.getData();
            final Bundle extras = new Bundle();
            final Iterator<Entry<String, String>> iter = payloadData.entrySet().iterator();
            while(iter.hasNext())
            {
            final Entry<String, String>  entry =iter.next();
            extras.putString(entry.getKey(), entry.getValue());
            }
    
            SharedPreferences settings = this.getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
            String mesg = payloadData.get("_msg");
            String title = payloadData.get("title");
            String url = payloadData.get("url");
            String messageId = payloadData.get("_mId");
            String deliveryId = payloadData.get("_dId");
            YourApplicationActivity.handleNotification(this, mesg, title, url, messageId, deliveryId, extras);
            }
        }
    
    code language-sql
    public static void handleNotification(Context context, String message, String title, String url, String messageId, String deliveryId, Bundle extras)
    {
        if( message == null ) message = "No Content";
        if( title == null )   title = "No title";
        if( url == null )     url = "http://www.tripadvisor.fr";
        int iconId = R.drawable.notif_neotrip;
    
        // notify Adobe Campaign that a notification just arrived
        SharedPreferences settings = context.getSharedPreferences(NeoTripActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
        Neolane.getInstance().setIntegrationKey(settings.getString(NeoTripActivity.APPUUID_NAME, NeoTripActivity.DFT_APPUUID));
        Neolane.getInstance().setMarketingHost(settings.getString(NeoTripActivity.SOAPRT_NAME, NeoTripActivity.DFT_SOAPRT));
        Neolane.getInstance().setTrackingHost(settings.getString(NeoTripActivity.TRACKRT_NAME, NeoTripActivity.DFT_TRACKRT));
    
        NeolaneAsyncRunner nas = new NeolaneAsyncRunner(Neolane.getInstance());
        nas.notifyReceive(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
        public void onNeolaneException(NeolaneException arg0, Object arg1) {}
        public void onIOException(IOException arg0, Object arg1) {}
        public void onComplete(String arg0, Object arg1){}
        });
        if (yourApplication.isActivityVisible())
        {
        Log.i("INFO", "The application has the focus" );
        ...
        }
        else
        {
        // notification creation
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification;
    
        // Activity to start
        Intent notifIntent = new Intent(context.getApplicationContext(), NotificationActivity.class);
        notifIntent.putExtra("notificationText", message);
        notifIntent.putExtra(NotificationActivity.NOTIFICATION_URL_KEYNAME, url);
        notifIntent.putExtra("_dId", deliveryId);
        notifIntent.putExtra("_mId", messageId);
        notifIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    
        notification = new Notification.Builder(context)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(iconId)
                .setContentIntent(contentIntent)
                .build();
    
        // launch the notification
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1234, notification);
        }
    }
    
  5. 跟踪数据消息的打开次数

    对于数据消息,您可以使用notifyOpening函数跟踪用户何时单击通知以将其打开。 用户单击通知时将创建通知活动(在onMessageReceived函数调用期间创建)

    code language-sql
    public class NotificationActivity extends Activity {
        public void onCreate(Bundle savedBundle) {
            [...]
            Bundle extra = getIntent().getExtras();
            if (extra != null) {
                // reinit the Campaign sdk
                SharedPreferences settings = getSharedPreferences(NeoTripActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
                Neolane.getInstance().setIntegrationKey(settings.getString(NeoTripActivity.APPUUID_NAME, NeoTripActivity.DFT_APPUUID));
                Neolane.getInstance().setMarketingHost(settings.getString(NeoTripActivity.SOAPRT_NAME, NeoTripActivity.DFT_SOAPRT));
                Neolane.getInstance().setTrackingHost(settings.getString(NeoTripActivity.TRACKRT_NAME, NeoTripActivity.DFT_TRACKRT));
    
                // Get the messageId and the deliveryId to perform tracking
                String deliveryId = extra.getString("_dId");
                String messageId = extra.getString("_mId");
    
                if (deliveryId != null && messageId != null)
                {
                    try {
                    Neolane.getInstance().notifyOpening(messageId, Integer.valueOf(deliveryId));
                    } catch (NeolaneException e) {
                    // ...
                    } catch (IOException e) {
                    // ...
                    }
                }
            }
        }
    }
    
  6. 跟踪通知消息的打开次数和点击次数

    对于通知消息,需要使用应用程序启动活动中的notifyOpening函数完成打开/点击跟踪,如下所示:

    code language-sql
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    
        SharedPreferences settings = getSharedPreferences(NeoTripActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
    
        // initialize Campaign SDK
        Neolane.getInstance().setIntegrationKey(settings.getString(NeoTripActivity.APPUUID_NAME, NeoTripActivity.DFT_APPUUID));
        Neolane.getInstance().setMarketingHost(settings.getString(NeoTripActivity.SOAPRT_NAME, NeoTripActivity.DFT_SOAPRT));
        Neolane.getInstance().setTrackingHost(settings.getString(NeoTripActivity.TRACKRT_NAME, NeoTripActivity.DFT_TRACKRT));
    ...
    ...
    ...
    
        // Manage opening/receive tracking of message notification
        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        String messageId = null, deliveryId = null;
        if( data != null ) {
        if (data.containsKey("_mId")) messageId = data.get("_mId").toString();
        if (data.containsKey("_dId")) deliveryId = data.get("_dId").toString();
        if ( messageId != null && deliveryId != null) {
            Log.i(TAG, "Notify opening from backgroun click_action");
            NeolaneAsyncRunner nas = new NeolaneAsyncRunner(Neolane.getInstance());
            nas.notifyOpening(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
            public void onNeolaneException(NeolaneException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_sdk_error) + arg0.getErrorCode());
            }
            public void onIOException(IOException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_io_error) +  arg0.getLocalizedMessage());
            }
            public void onComplete(String arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_ok));
            }
            });
            nas.notifyReceive(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
            public void onNeolaneException(NeolaneException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_sdk_error) + arg0.getErrorCode());
            }
            public void onIOException(IOException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_io_error) +  arg0.getLocalizedMessage());
            }
            public void onComplete(String arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_ok));
            }
            });
        }
        }
    }
    
    note note
    NOTE
    如果用户正在目标活动中使用click_action选项,则需要执行类似的管理。
  7. 接收数据消息的跟踪

    对于数据消息,跟踪在onMessageReceived调用级别接收。 需要调用“notifyReceive”函数。

    YourApplicationMessagingService.java

    code language-sql
    package com.android.YourApplication;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;
    
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    
    
    public class YourApplicationFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    
    @Override
    public void onMessageReceived(RemoteMessage message)
        {
            Log.d(TAG, "Receive message from: " + message.getFrom());
            Map<String,String> payloadData = message.getData();
            final Bundle extras = new Bundle();
            final Iterator<Entry<String, String>> iter = payloadData.entrySet().iterator();
            while(iter.hasNext())
            {
            final Entry<String, String>  entry =iter.next();
            extras.putString(entry.getKey(), entry.getValue());
            }
    
            SharedPreferences settings = this.getSharedPreferences(YourApplicationActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
            String mesg = payloadData.get("_msg");
            String title = payloadData.get("title");
            String url = payloadData.get("url");
            String messageId = payloadData.get("_mId");
            String deliveryId = payloadData.get("_dId");
            YourApplicationActivity.handleNotification(this, mesg, title, url, messageId, deliveryId, extras);
        }
    }
    
    code language-sql
    public static void handleNotification(Context context, String message, String title, String url, String messageId, String deliveryId, Bundle extras){
        .....
        .....
            // notify Campaign that a notification just arrived
            SharedPreferences settings = context.getSharedPreferences(NeoTripActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
            Neolane.getInstance().setIntegrationKey(settings.getString(NeoTripActivity.APPUUID_NAME, NeoTripActivity.DFT_APPUUID));
            Neolane.getInstance().setMarketingHost(settings.getString(NeoTripActivity.SOAPRT_NAME, NeoTripActivity.DFT_SOAPRT));
            Neolane.getInstance().setTrackingHost(settings.getString(NeoTripActivity.TRACKRT_NAME, NeoTripActivity.DFT_TRACKRT));
    
            NeolaneAsyncRunner nas = new NeolaneAsyncRunner(Neolane.getInstance());
            nas.notifyReceive(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
                public void onNeolaneException(NeolaneException arg0, Object arg1) {}
                public void onIOException(IOException arg0, Object arg1) {}
                public void onComplete(String arg0, Object arg1){}
        });
    }
    
  8. 接收通知消息的跟踪

    对于通知消息,跟踪接收必须在两个级别进行配置:

    • onMessageReceived (应用程序不在后台):已在上一节中完成实施
    • onCreate启动项活动(如果使用click_action函数,则为目标活动。) (应用程序不在后台)。

    它需要在打开/点击跟踪的同时完成。

    code language-sql
    /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
    
            SharedPreferences settings = getSharedPreferences(NeoTripActivity.APPLICATION_PREF_NAME, Context.MODE_PRIVATE);
    
            // initialize Campaign SDK
            Neolane.getInstance().setIntegrationKey(settings.getString(NeoTripActivity.APPUUID_NAME, NeoTripActivity.DFT_APPUUID));
            Neolane.getInstance().setMarketingHost(settings.getString(NeoTripActivity.SOAPRT_NAME, NeoTripActivity.DFT_SOAPRT));
            Neolane.getInstance().setTrackingHost(settings.getString(NeoTripActivity.TRACKRT_NAME, NeoTripActivity.DFT_TRACKRT));
    ...
    ...
    ...
    
        // Manage opening/receive tracking of message notification
        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        String messageId = null, deliveryId = null;
        if( data != null ) {
        if (data.containsKey("_mId")) messageId = data.get("_mId").toString();
        if (data.containsKey("_dId")) deliveryId = data.get("_dId").toString();
        if ( messageId != null && deliveryId != null) {
            Log.i(TAG, "Notify opening from backgroun click_action");
            NeolaneAsyncRunner nas = new NeolaneAsyncRunner(Neolane.getInstance());
            nas.notifyOpening(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
            public void onNeolaneException(NeolaneException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_sdk_error) + arg0.getErrorCode());
            }
            public void onIOException(IOException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_io_error) +  arg0.getLocalizedMessage());
            }
            public void onComplete(String arg0, Object arg1) {
                toastMessage( "error", getString(R.string.open_track_ok));
            }
            });
            nas.notifyReceive(messageId, deliveryId, new NeolaneAsyncRunner.RequestListener() {
            public void onNeolaneException(NeolaneException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_sdk_error) + arg0.getErrorCode());
            }
            public void onIOException(IOException arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_io_error) +  arg0.getLocalizedMessage());
            }
            public void onComplete(String arg0, Object arg1) {
                toastMessage( "error", getString(R.string.rec_track_ok));
            }
            });
        }
        }
    }
    

集成iOS SDK

  1. 将移动设备注册到Adobe Campaign服务器

    注册功能使您能够:

    • 将通知ID或推送ID(iOS的deviceToken和Android的注册ID)发送到Adobe Campaign。
    • 恢复协调密钥或userKey(例如,电子邮件或帐号)
    code language-sql
    // Callback called on successful registration to the APNs
     - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
    {
      // Pass the token to Adobe Campaign
      Neolane_SDK *nl = [Neolane_SDK getInstance];
      [nl registerDevice:tokenString:self.userKey:dic];
    }
    
  2. 启用跟踪函数

    跟踪函数允许您跟踪何时激活通知(打开)。

    code language-sql
    (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)launchOptions
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    {
    if( launchOptions ) { // Retrieve notification parameters here ... // Track application opening Neolane_SDK
    *nl = [Neolane_SDK getInstance]; [nl track:launchOptions:NL_TRACK_CLICK]; }
    ...
    completionHandler(UIBackgroundFetchResultNoData);
    }
    
  3. 静默通知跟踪

    iOS允许您发送静默通知、通知或数据,这些信息或数据将直接发送到移动应用程序,而不会显示通知。 Adobe Campaign允许您跟踪他们。

    要跟踪静默通知,请按照以下示例操作:

    code language-sql
    // AppDelegate.m
    ...
    ...
    #import "AppDelegate.h"
    #import "Neolane_SDK.h"
    ...
    ...
    // Callback called when the application is already launched (whether the application is running foreground or background)
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)launchOptions fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    {
    NSLog(@"IN didReceiveRemoteNotification:fetchCompletionHandler");
    if (launchOptions) NSLog(@"IN launchOptions: %@", [launchOptions description]);
    NSLog(@"Application state: %ld", (long)application.applicationState);
    
    // Silent Notification (specific case, can use NL_TRACK_RECEIVE as the user does not have click/open the notification)
    if ([launchOptions[@"aps"][@"content-available"] intValue] == 1 )
        {
    NSLog(@"Silent Push Notification");
    ...
    ...
    //Call receive tracking
            Neolane_SDK *nl = [Neolane_SDK getInstance];
    [nl track:launchOptions:NL_TRACK_RECEIVE];
    
    completionHandler(UIBackgroundFetchResultNoData); //Do not show notification
    return;
    }
    ...
    ...
            completionHandler(UIBackgroundFetchResultNoData);
    }
    
  4. 配置注册状态

    委派协议允许您获取​ registerDevice ​调用的结果,并可用于了解注册过程中是否出现错误。

    registerDeviceStatus ​原型为:

    code language-sql
    - (void) registerDeviceStatus: (ACCRegisterDeviceStatus) status:(NSString *) errorReason;
    
    • 状态 ​允许您知道注册是否成功或发生错误。

    • ErrorReason ​为您提供有关所发生错误的详细信息。 有关可用错误及其说明的更多信息,请参阅下表。

    table 0-row-3 1-row-3 2-row-3 3-row-3 4-row-3 5-row-3 6-row-3 layout-auto
    状态 说明 错误原因
    ACCRegisterDeviceStatusSuccess 注册成功 EMPTY
    ACCRegisterDeviceStatusFailureMarketingServerHostnameEmpty ACC营销服务器主机名为空或未设置。 EMPTY
    ACCRegisterDeviceStatusFailureIntegrationKeyEmpty 集成键为空或未设置。 EMPTY
    ACCRegisterDeviceStatusFailureConnectionIssue 与ACC的连接问题 更多信息(以操作系统当前语言提供)
    ACCRegisterDeviceStatusFailureUnknownUUID 提供的UUID(集成密钥)未知。 EMPTY
    ACCRegisterDeviceStatusFailureUnexpectedError ACC服务器返回意外错误。 错误消息返回到ACC。

    Neolane_SDKDelegate ​协议和​ registerDeviceStatus ​委托定义如下:

    code language-sql
    //  Neolane_SDK.h
    //  Campaign SDK
    ..
    ..
    // Register Device Status Enum
    typedef NS_ENUM(NSUInteger, ACCRegisterDeviceStatus) {
    ACCRegisterDeviceStatusSuccess,                               // Resistration Succeed
    ACCRegisterDeviceStatusFailureMarketingServerHostnameEmpty,   // The Campaign marketing server hostname is Empty or not set
    ACCRegisterDeviceStatusFailureIntegrationKeyEmpty,            // The integration key is empty or not set
    ACCRegisterDeviceStatusFailureConnectionIssue,                // Connection issue with Campaign, more information in errorReason
    ACCRegisterDeviceStatusFailureUnknownUUID,                    // The provided UUID (integration key) is unknown
    ACCRegisterDeviceStatusFailureUnexpectedError                 // Unexpected error returned by Campaign server, more information in errorReason
    };
    // define the protocol for the registerDeviceStatus delegate
    @protocol Neolane_SDKDelegate <NSObject>
    @optional
    - (void) registerDeviceStatus: (ACCRegisterDeviceStatus) status :(NSString *) errorReason;
    @end
    @interface Neolane_SDK: NSObject {
    }
    ...
    ...
    // registerDeviceStatus delegate
    @property (nonatomic, weak) id <Neolane_SDKDelegate> delegate;
    ...
    ...
    @end
    

    要实施​ registerDeviceStatus ​委派,请执行以下步骤:

    1. 在SDK初始化期间实施​ setDelegate

      code language-sql
      // AppDelegate.m
      ...
      ...
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
      ...
      ...
          // Get the stored settings
      
          NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
          NSString *strMktHost = [defaults objectForKey:@"mktHost"];
          NSString *strTckHost = [defaults objectForKey:@"tckHost"];
          NSString *strIntegrationKey = [defaults objectForKey:@"integrationKey"];
          userKey = [defaults objectForKey:@"userKey"];
      
          // Configure Campaign SDK on first launch
          Neolane_SDK *nl = [Neolane_SDK getInstance];
          [nl setMarketingHost:strMktHost];
          [nl setTrackingHost:strTckHost];
          [nl setIntegrationKey:strIntegrationKey];
          [nl setDelegate:self];    // HERE
      ...
      ...
      }
      
    2. 在类的​ @interface ​中添加协议。

      code language-sql
      //  AppDelegate.h
      
      #import <UIKit/UIKit.h>
      #import <CoreLocation/CoreLocation.h>
      #import "Neolane_SDK.h"
      
      @class LandingPageViewController;
      
      @interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, Neolane_SDKDelegate> {
          CLLocationManager *locationManager;
          NSString *userKey;
          NSString *mktServerUrl;
          NSString *tckServerUrl;
          NSString *homeURL;
          NSString *strLandingPageUrl;
          NSTimer *timer;
      }
      
    3. 在​ AppDelegate ​中实施委托。

      code language-sql
      //  AppDelegate.m
      
      #import "AppDelegate.h"
      #import "Neolane_SDK.h"
      #import "LandingPageViewController.h"
      #import "RootViewController.h"
      ...
      ...
      - (void) registerDeviceStatus: (ACCRegisterDeviceStatus) status :(NSString *) errorReason
      {
          NSLog(@"registerStatus: %lu",status);
      
          if ( errorReason != nil )
              NSLog(@"errorReason: %@",errorReason);
      
          if( status == ACCRegisterDeviceStatusSuccess )
          {
              // Registration successful
              ...
              ...
          }
          else { // An error occurred
              NSString *message;
              switch ( status ){
                  case ACCRegisterDeviceStatusFailureUnknownUUID:
                      message = @"Unkown IntegrationKey (UUID)";
                      break;
                  case ACCRegisterDeviceStatusFailureMarketingServerHostnameEmpty:
                      message = @"Marketing URL not set or Empty";
                      break;
                  case ACCRegisterDeviceStatusFailureIntegrationKeyEmpty:
                      message = @"Integration Key not set or empty";
                      break;
                  case ACCRegisterDeviceStatusFailureConnectionIssue:
                      message = [NSString stringWithFormat:@"%@ %@",@"Connection issue:",errorReason];
                      break;
                  case ACCRegisterDeviceStatusFailureUnexpectedError:
                  default:
                      message = [NSString stringWithFormat:@"%@ %@",@"Unexpected Error",errorReason];
                      break;
              }
          ...
          ...
          }
      }
      @end
      

变量 variables

利用变量,可定义在收到通知后的移动应用程序行为。 必须在移动设备应用程序代码以及Adobe Campaign客户端控制台的专用移动设备应用程序的​ Variables ​选项卡中定义这些变量。

下面是一个代码示例,该代码允许移动应用程序收集通知中添加的任何变量。 在我们的示例中,我们使用“VAR”变量。

  • 在Android

    code language-sql
    public void onReceive(Context context, Intent intent) {
         ...
        String event = intent.getStringExtra("VAR");
         ...
    }
    
  • 在iOS

    code language-sql
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        ....
        if( launchOptions )
        {
            // When application is not already launched, the notification data if any are stored in the key 'UIApplicationLaunchOptionsRemoteNotificationKey'
            NSDictionary *localLaunchOptions = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
            if( localLaunchOptions )
            {
             ...
             [localLaunchOptions objectForKey:@"VAR"];
            ...
            }
       }
    }
    
    // Callback called when the application is already launched (whether the application is running foreground or background)
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)launchOptions
    {
        if( launchOptions )
        {
         ...
            [launchOptions objectForKey:@"VAR"];
        }
    }
    
CAUTION
Adobe建议选择短变量名称,因为iOS和Android的通知大小限制为4kB。

通知服务扩展 notification-service-extension

用于iOS的​

介质必须在通知服务扩展级别下载。

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    NSDictionary *userInfo = nil;
    NSString *url = nil;

    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    userInfo = request.content.userInfo;
    if ( userInfo != nil )
    {
        url = userInfo[@"mediaUrl"];  // Get the url of the media to download (Adobe Campaign additional variable)
    }
    ...
    // Perform the download to local storage

通知内容扩展 notification-content-extension

用于iOS的​

在此级别,您需要:

  • 将您的内容扩展关联到Adobe Campaign发送的类别:

    如果您希望移动设备应用程序显示图像,则可以在Adobe Campaign中将类别值设置为“图像”,并在移动设备应用程序中创建将​ UNNotificationExtensionCategory ​参数设置为“图像”的通知扩展。 当在设备上收到推送通知时,根据定义的类别值调用扩展。

  • 定义通知布局

    您需要使用相关构件定义布局。 对于图像,该构件名为​ UIImageView

  • 显示您的媒体

    您需要添加代码以将媒体数据馈送到构件。 以下是图像的代码示例:

    code language-sql
    #import "NotificationViewController.h"
    #import <UserNotifications/UserNotifications.h>
    #import <UserNotificationsUI/UserNotificationsUI.h>
    
    @interface NotificationViewController () <UNNotificationContentExtension>
    
    @property (strong, nonatomic) IBOutlet UIImageView *imageView;
    @property (strong, nonatomic) IBOutlet UILabel *notifContent;
    @property (strong, nonatomic) IBOutlet UILabel *label;
    
    @end
    
    @implementation NotificationViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any required interface initialization here.
    }
    
    - (void)didReceiveNotification:(UNNotification *)notification {
        self.label.text = notification.request.content.title;
        self.notifContent.text = notification.request.content.body;
        UNNotificationAttachment *attachment = [notification.request.content.attachments objectAtIndex:0];
        if ([attachment.URL startAccessingSecurityScopedResource])
        {
          NSData * imageData = [[NSData alloc] initWithContentsOfURL:attachment.URL];
          self.imageView.image =[UIImage imageWithData: imageData];
          [attachment.URL stopAccessingSecurityScopedResource];
        }
    }
    @end
    
recommendation-more-help
35662671-8e3d-4f04-a092-029a056c566b