Utilizza gli SDK Campaign per iOS e Android per facilitare l’integrazione dell’app mobile nella piattaforma Adobe Campaign.
Le versioni supportate da Android e iOS e le versioni compatibili con Campaign SDK per Campaign v8 sono elencate nella Matrice di compatibilità.
In qualità di amministratore di Campaign, puoi scaricare gli SDK di Campaign dal Distribuzione di software di Experience Cloud. Per ulteriori informazioni, contatta Adobe Customer Care.
Per integrare l’SDK di Campaign nell’app mobile, l’amministratore funzionale deve fornire allo sviluppatore le seguenti informazioni:
Una chiave di integrazione: per abilitare la piattaforma Adobe Campaign per identificare l’app mobile.
Questa chiave di integrazione viene immessa nella console Adobe Campaign, nella Information scheda di servizio dedicata all’app mobile. Fai riferimento a Documentazione di Campaign Classic v7.
Un URL di tracciamento: che corrisponde all’indirizzo del server di tracciamento di Adobe Campaign.
Un URL di marketing: per abilitare la raccolta degli abbonamenti.
In Android:
Neolane.getInstance().setIntegrationKey("your Adobe mobile app integration key");
Neolane.getInstance().setMarketingHost("https://yourMarketingHost:yourMarketingPort/");
Neolane.getInstance().setTrackingHost("https://yourTrackingHost:yourTrackingPort/");
In iOS:
Neolane_SDK *nl = [Neolane_SDK getInstance];
[nl setMarketingHost:strMktHost];
[nl setTrackingHost:strTckHost];
[nl setIntegrationKey:strIntegrationKey];
Android SDK è una libreria jar scritta in JAVA. Consente agli sviluppatori Android di integrarsi con Adobe Campaign: registra un nuovo dispositivo, collega il dispositivo a un utente, tiene traccia del comportamento e altro ancora.
In questa sezione, scopri come utilizzare l’SDK per Android in un’applicazione Android che implementa Google Firebase Cloud Messaging (FCM).
Per Campaign v8, utilizza Campaign Android SDK v1.1.1.
Per utilizzare la notifica push su Android, è necessario disporre di un account FCM, configurare l'applicazione Android per ricevere la notifica e collegare l'applicazione all'account FCM. Ulteriori informazioni in Documentazione di Google.
Fai riferimento a Documentazione di Google per aggiungere Firebase al tuo progetto Android.
Scopri come implementare FCM nella tua applicazione in Documentazione di Google.
Non dimenticare di scaricare e aggiungere google-services.json al tuo progetto.
La apiKey
deve corrispondere a projectKey
impostato nell'applicazione mobile Adobe Campaign collegata a questa applicazione Android.
Inizializzare l'SDK
Prima di usare l'SDK per Android, è necessario inizializzarlo. L'inizializzazione dell'SDK può essere eseguita nel onCreate
funzione di un’attività.
/** 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));
...
}
La IntegrationKey
deve corrispondere al valore 'IntegrationKey' impostato nell'applicazione mobile Adobe Campaign collegata a questa applicazione Android.
Registra il dispositivo mobile nel server Adobe Campaign
La funzione di registrazione consente di:
Devi registrare il dispositivo su Adobe Campaign, all'inizializzazione dell'app o all'azione dell'utente. Può essere facilmente fatto utilizzando registerDevice
metodo .
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
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);
}
});
}
Notifica a Campaign quando il token del dispositivo mobile dell’utente cambia
Ti consigliamo di utilizzare il registerDevice
quando si chiama onTokenRefresh
per notificare ad Adobe Campaign la modifica del token del dispositivo mobile dell’utente.
Ad esempio:
YourApplicationFirebaseInstanceIDService.java
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);
}
}
}
Configurare il servizio di messaggistica Firebase
Estendi la FirebaseMessagingService
in onMessageReceived
callback per ricevere i messaggi. Ti consigliamo di chiamare il notifyReceive
quando onMessageReceived
viene chiamato per abilitare il tracciamento della ricezione delle notifiche sul dispositivo mobile. In Adobe Campaign questo nome è print notifica: questa funzione deve essere chiamata immediatamente prima di richiedere al sistema operativo di visualizzare la notifica.
YourApplicationMessagingService.java
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);
}
}
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);
}
}
Tracciare l’apertura dei messaggi dati
Per i messaggi di dati, puoi tenere traccia di quando un utente fa clic su una notifica per aprirla, utilizzando la notifyOpening
funzione . L’attività di notifica viene creata quando l’utente fa clic sulla notifica (creata durante onMessageReceived
chiamata di funzione)
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) {
// ...
}
}
}
}
}
Tracciare aperture e clic sui messaggi di notifica
Per i messaggi di notifica, è necessario eseguire il tracciamento di apertura/clic con il notifyOpening
all'interno dell'attività di avvio dell'applicazione, come segue:
/** 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));
}
});
}
}
}
È necessario eseguire una gestione simile se l’utente utilizza click_action
all’interno dell’attività di destinazione.
Tracciamento della ricezione dei messaggi di dati
Per i messaggi di dati, il tracciamento viene ricevuto nella onMessageReceived
livello di chiamata. È necessario chiamare la funzione 'notifyReceive'.
YourApplicationMessagingService.java
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);
}
}
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){}
});
}
Tracciamento della ricezione dei messaggi di notifica
Per i messaggi di notifica, la ricezione del tracciamento deve essere configurata a due livelli:
onMessageReceived
(applicazione non in background): l’implementazione è stata eseguita nella sezione precedenteonCreate
dell’attività di lancio (o dell’attività con targeting se click_action
viene utilizzata la funzione .) (Applicazione non in background).Deve essere eseguito contemporaneamente al tracciamento aperto/clic.
/** 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));
}
});
}
}
}
Registra il dispositivo mobile nel server Adobe Campaign
La funzione di registrazione consente di:
// 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];
}
Abilita funzione di tracciamento
La funzione di tracciamento ti consente di tenere traccia di quando vengono attivate le notifiche (si apre).
(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);
}
Tracciamento delle notifiche silenziose
iOS ti consente di inviare notifiche silenziose, notifiche o dati che verranno inviati direttamente a un’app mobile senza visualizzarli. Adobe Campaign ti consente di seguirli.
Per tenere traccia della notifica silenziosa, segui l’esempio seguente:
// 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);
}
Configurare lo stato di registrazione
Il protocollo delegato ti consente di ottenere il risultato della registerDevice chiama e può essere utilizzato per sapere se si è verificato un errore durante la registrazione.
La registerDeviceStatus prototipo:
- (void) registerDeviceStatus: (ACCRegisterDeviceStatus) status:(NSString *) errorReason;
Stato consente di sapere se una registrazione è riuscita o se si è verificato un errore.
ErrorReason fornisce ulteriori informazioni sugli errori che si sono verificati. Per ulteriori informazioni sugli errori disponibili e sulle relative descrizioni, consulta la tabella seguente.
Stato | Descrizione | ErrorReason |
---|---|---|
ACCRegisterDeviceStatusSuccess | Registrazione riuscita | VUOTO |
ACCRegisterDeviceStatusFailureMarketingServerHostnameEmpty | Il nome host del server di marketing ACC è vuoto o non è impostato. | VUOTO |
ACCRegisterDeviceStatusFailureIntegrationKeyEmpty | La chiave di integrazione è vuota o non impostata. | VUOTO |
ACCRegisterDeviceStatusFailureConnectionIssue | Problema di connessione con ACC | Ulteriori informazioni (nella lingua corrente del sistema operativo) |
ACCRegisterDeviceStatusFailureUnknownUUID | L'UUID fornito (chiave di integrazione) è sconosciuto. | VUOTO |
ACCRegisterDeviceStatusFailureUnexpectedError | Errore imprevisto restituito al server ACC. | Il messaggio di errore è stato restituito ad ACC. |
Neolane_SDKDelegate protocollo e registerDeviceStatus la definizione di delegato è la seguente:
// 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
Implementazione registerDeviceStatus delegare, segui questi passaggi:
Implementare setDelegate durante l'inizializzazione dell'SDK.
// 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
...
...
}
Aggiungi il protocollo nel @interface della tua classe.
// 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;
}
Implementa il delegato nel AppDelegate.
// 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
Le variabili ti consentono di definire il comportamento dell’app mobile dopo aver ricevuto una notifica. Queste variabili devono essere definite nel codice dell’app mobile e nella console Adobe Campaign, nella Variables nel servizio dedicato per le app mobili.
Ulteriori informazioni in Documentazione di Campaign Classic v7 nell’app mobile: Passaggi di configurazione per iOS and Configuration steps for Andoid.
Di seguito è riportato un esempio di codice che consente a un’app mobile di raccogliere tutte le variabili aggiunte in una notifica. Nel nostro esempio, utilizziamo la variabile "VAR".
In Android:
public void onReceive(Context context, Intent intent) {
...
String event = intent.getStringExtra("VAR");
...
}
In iOS:
- (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"];
}
}
Adobe consiglia di scegliere nomi di variabili brevi perché le dimensioni di notifica sono limitate a 4kB per iOS e Android.
Per iOS
I file multimediali devono essere scaricati a livello di estensione del servizio di notifica.
#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
Per iOS
A questo livello, è necessario:
Associa l’estensione del contenuto alla categoria inviata da Adobe Campaign:
Se desideri che l’app mobile visualizzi un’immagine, puoi impostare il valore della categoria su "image" in Adobe Campaign e nella tua app mobile, crea un’estensione di notifica con il UNNotificationExtensionCategory impostato su "image". Quando la notifica push viene ricevuta sul dispositivo, l'estensione viene chiamata in base al valore di categoria definito.
Definire il layout delle notifiche
È necessario definire un layout con i widget pertinenti. Per un'immagine, il widget viene denominato UIImageView.
Visualizzare i supporti
Devi aggiungere del codice per inviare i dati multimediali al widget. Ecco un esempio di codice per un'immagine:
#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