Paso 3: Maneje los valores de los parámetros de Remote Config en el código de su aplicación
Introducción: Optimice la frecuencia de los anuncios de AdMob con Firebase |
Paso 1: utilice AdMob para crear nuevas variantes de bloques de anuncios para realizar pruebas |
Paso 2: configurar una prueba A/B en Firebase console |
Paso 3: Maneje los valores de los parámetros de Remote Config en el código de su aplicación |
Paso 4: inicie la prueba A/B y revise los resultados de la prueba en Firebase console |
Paso 5: Decida si implementará el nuevo formato de anuncio |
Al final del último paso, creó un parámetro de Remote Config ( INTERSTITIAL_AD_KEY
). En este paso, agregará la lógica al código de su aplicación para lo que su aplicación debería mostrar según el valor de ese parámetro.
Agregue los SDK necesarios
Antes de usar Remote Config en el código de su aplicación, agregue el SDK de Remote Config y el SDK de Firebase para Google Analytics a los archivos de compilación de su proyecto.
Agregue e instale los siguientes pods en su podfile:
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
Agregue e instale los siguientes pods en su podfile:
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
Agregue las siguientes dependencias de biblioteca a su archivo build.gradle
:
implementation 'com.google.android.gms:play-services-ads:23.0.0'
implementation 'com.google.firebase:firebase-analytics:21.6.1'
implementation 'com.google.firebase:firebase-config:21.6.3'
Descargue e instale el SDK de Firebase Unity, luego agregue los siguientes paquetes de Unity a su proyecto:
-
FirebaseAnalytics.unitypackage
-
FirebaseRemoteConfig.unitypackage
Configurar la instancia de Remote Config
Para usar los valores de los parámetros de Remote Config, configure la instancia de Remote Config para que esté configurada para recuperar nuevos valores para la instancia de la aplicación cliente.
En este ejemplo, Remote Config está configurado para comprobar si hay nuevos valores de parámetros una vez cada hora.
remoteConfig = RemoteConfig.remoteConfig()
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 3600
remoteConfig.configSettings = settings
self.remoteConfig = [FIRRemoteConfig remoteConfig];
FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] init];
remoteConfigSettings.minimumFetchInterval = 3600;
self.remoteConfig.configSettings = remoteConfigSettings;
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(3600)
.build();
mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
remoteConfig = Firebase.remoteConfig
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = 3600
}
remoteConfig.setConfigSettingsAsync(configSettings)
var remoteConfig = FirebaseRemoteConfig.DefaultInstance;
var configSettings = new ConfigSettings {
MinimumFetchInternalInMilliseconds =
(ulong)(new TimeSpan(1, 0, 0).TotalMilliseconds)
};
remoteConfig.SetConfigSettingsAsync(configSettings)
.ContinueWithOnMainThread(task => {
Debug.Log("Config settings confirmed");
}
Obtener y activar Remote Config
Obtenga y active los parámetros de Remote Config para que pueda comenzar a usar los nuevos valores de los parámetros.
Querrá realizar esta llamada lo antes posible en la fase de carga de su aplicación porque esta llamada es asincrónica y necesitará obtener previamente el valor de Remote Config para que su aplicación sepa qué anuncio mostrar.
remoteConfig.fetch() { (status, error) -> Void in
if status == .success {
print("Config fetched!")
self.remoteConfig.activate() { (changed, error) in
// ...
}
} else {
print("Config not fetched")
print("Error: \(error?.localizedDescription ?? "No error available.")")
}
self.loadAdUnit()
}
[self.remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
if (status == FIRRemoteConfigFetchStatusSuccess) {
NSLog(@"Config fetched!");
[self.remoteConfig activateWithCompletion:^(BOOL changed, NSError * _Nullable error) {
// ...
}];
} else {
NSLog(@"Config not fetched");
NSLog(@"Error %@", error.localizedDescription);
}
[self loadAdUnit];
}];
mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
@Override
public void onComplete(@NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
boolean updated = task.getResult();
Log.d(TAG, "Config params updated: " + updated);
} else {
Log.d(TAG, "Config params failed to update");
}
loadAdUnit();
}
});
remoteConfig.fetchAndActivate()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val updated = task.result
Log.d(TAG, "Config params updated: $updated")
} else {
Log.d(TAG, "Config params failed to update")
}
loadAdUnit()
}
remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted) {
Debug.LogWarning("Config params failed to update");
} else {
Debug.Log("Config params updated: " + task.Result);
}
LoadAdUnit();
});
Su aplicación ahora está lista para manejar el parámetro de Remote Config que creó durante la prueba A/B configurada anteriormente en este tutorial.
Utilice el valor del parámetro Remote Config
Utilice el valor de Remote Config obtenido previamente en la función loadAdUnit()
para determinar qué variante de frecuencia de anuncios debe mostrarse para esta instancia de aplicación.
private func loadAdUnit() {
let adUnitId = remoteConfig["INTERSTITIAL_AD_KEY"].stringValue;
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID: adUnitId,
request: request,
completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load: \(error.localizedDescription)")
return
}
interstitial = ad
// Register for callbacks.
}
)
}
// Register for callbacks.
- (void)loadAdUnit {
NSString *adUnitId =
self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;
GADRequest *request = [GADRequest request];
[GADInterstitialAd loadAdWithAdUnitId:adUnitId
request:request
completionHandler:^(GADInterstitialAd *ad,
NSError *error) {
if (error) {
NSLog(@"Failed to load interstitial ad with error: %@",
[error localizedDescription]);
return;
}
self.interstitial = ad;
}];
}
private void loadAdUnit() {
String adUnitId =
mFirebaseRemoteConfig.getString("INTERSTITIAL_AD_KEY");
// Load Interstitial Ad (assume adUnitId not null)
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this, adUnitId, adRequest, new
InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd intertitialAd) {
mInterstitialAd = interstitialAd;
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
}
});
}
private fun loadAdUnit() {
String adUnitId = remoteConfig.getString("INTERSTITIAL_AD_KEY")
var adRequest = AdRequestBuilder.Builder().build()
AdRequestBuilder.load(this, adUnitId, adRequest, object :
InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
mInterstitialAd = interstitialAd
}
})
}
void LoadAdUnit() {
// Note that you may want to encode and parse two sets of ad unit IDs for
// Android / iOS in the Unity implementation.
String adUnitId = remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue;
this.interstitial = new InterstitialAd(adUnitId);
}
Agregue otras comprobaciones para el valor del parámetro
Hay otras áreas en el código de su aplicación donde deberá verificar el valor de este parámetro de Remote Config para determinar qué experiencia publicitaria se cargará. Por ejemplo, puede decidir si desea volver a cargar un anuncio después de que el usuario haya terminado de ver el actual.
Las llamadas de recuperación y activación deben realizarse primero para obtener cualquier cambio en el valor de los parámetros, por ejemplo, si decide finalizar o crear un nuevo experimento.
Desde allí, siempre puede verificar el valor del parámetro mediante las siguientes llamadas:
remoteConfig["INTERSTITIAL_AD_KEY"].stringValue
self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;
mFirebaseRemoteConfig.getString(INTERSTITIAL_AD_KEY)
remoteConfig.getString(INTERSTITIAL_AD_KEY)
remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue
Estas llamadas siempre devolverán el mismo valor para una instancia de aplicación dependiendo de si se colocó en el grupo de control o en uno de los nuevos grupos de variantes de anuncios, a menos que se hayan realizado cambios en Firebase console que se obtuvieron y activaron en las llamadas anteriores.
Paso 2 : configurar una prueba A/B en Firebase consolePaso 4 : iniciar la prueba A/B y revisar los resultados de la prueba