將 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
    此整合金鑰是在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行動應用程式中所設定的projectKey。

設定Android SDK

  1. 初始化SDK

    在使用Android SDK之前,您必須先初始化它。 可在活動的onCreate函式中完成SDK初始化。

    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中,此通知名為​ 列印 ​通知:在要求作業系統顯示通知之前,應該呼叫此函式。

    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
    如果使用者在目標活動內使用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
    狀態 說明 ErrorReason
    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

變數可讓您定義在收到通知後的行動應用程式行為。 這些變數必須在行動應用程式程式碼中,以及專用行動應用程式之​ Variables ​索引標籤的Adobe Campaign使用者端主控台中定義。

以下是程式碼範例,此程式碼可讓行動應用程式收集通知中新增的任何變數。 在範例中,我們使用「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中將類別值設為"image",並在行動應用程式中,使用​ UNNotificationExtensionCategory ​引數設定為"image"來建立通知擴充功能。 在裝置上收到推播通知時,會根據定義的類別值呼叫擴充功能。

  • 定義您的通知配置

    您必須使用相關Widget來定義版面。 對於影像,Widget的名稱為​UIImageView。

  • 顯示您的媒體

    您需要新增程式碼,以將媒體資料摘要至Widget。 以下是影像的程式碼範例:

    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
campaign-help-v8