מדריך: אופטימיזציה של תדירות המודעות ב-AdMob

שלב 3: טיפול בערכי הפרמטרים של Remote Config בקוד של האפליקציה



בסוף השלב האחרון יצרתם פרמטר Remote Config (INTERSTITIAL_AD_KEY). בשלב הזה תוסיפו לקוד של האפליקציה את הלוגיקה של מה שהאפליקציה צריכה להציג על סמך הערך של הפרמטר הזה.

הוספת ערכות ה-SDK הנדרשות

לפני שמשתמשים ב-Remote Config בקוד האפליקציה, צריך להוסיף את ה-SDK של Remote Config ואת ה-SDK של Firebase ל-Google Analytics לקובצי ה-build של הפרויקט.

מוסיפים את ה-pods הבאים ל-Podfile ומתקינים אותם:

pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'

מוסיפים את ה-pods הבאים ל-Podfile ומתקינים אותם:

pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'

מוסיפים לקובץ build.gradle את יחסי התלות הבאים בספריות:

implementation 'com.google.android.gms:play-services-ads:24.0.0'
implementation 'com.google.firebase:firebase-analytics:22.3.0'
implementation 'com.google.firebase:firebase-config:22.1.0'

מורידים ומתקינים את Firebase Unity SDK, ואז מוסיפים לפרויקט את חבילות Unity הבאות:

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

הגדרת מכונה של Remote Config

כדי להשתמש בערכי הפרמטר Remote Config, צריך להגדיר את המכונה Remote Config כך שתשלוף ערכים חדשים למכונה של אפליקציית הלקוח.

בדוגמה הזו, Remote Config מוגדר לבדוק ערכים חדשים של פרמטרים פעם בשעה.

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");
}

אחזור והפעלה של Remote Config

מאחזרים ומפעילים את הפרמטרים Remote Config כדי שאפשר יהיה להתחיל להשתמש בערכי הפרמטרים החדשים.

מומלץ לבצע את הקריאה הזו מוקדם ככל האפשר בשלב הטעינה של האפליקציה, כי הקריאה הזו היא אסינכררונית וצריך לאחזר מראש את הערך של Remote Config כדי שהאפליקציה תדע איזו מודעה להציג.

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();
});

עכשיו האפליקציה מוכנה לטפל בפרמטר Remote Config שיצרתם במהלך הגדרת בדיקת ה-A/B מוקדם יותר במדריך הזה.

שימוש בערך הפרמטר Remote Config

משתמשים בערך Remote Config שאוחזר מראש בפונקציה loadAdUnit() כדי לקבוע איזה וריאנט של תדירות הצגת מודעות צריך להופיע למופע האפליקציה הזה.

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);
}

הוספת בדיקות אחרות לערך הפרמטר

יש אזורים אחרים בקוד האפליקציה שבהם תצטרכו לבדוק את הערך של הפרמטר Remote Config כדי לקבוע איזו חוויית צפייה במודעות תוריד. לדוגמה, אתם יכולים להחליט אם לטעון מחדש מודעה אחרי שהמשתמש מסיים לצפות במודעה הנוכחית.

קודם צריך לבצע את הקריאות לאחזור ולהפעלה כדי לקבל עדכונים לגבי ערכי הפרמטרים – לדוגמה, אם מחליטים לסיים ניסוי או ליצור ניסוי חדש.

לאחר מכן, תמיד תוכלו לבדוק את הערך של הפרמטר באמצעות הקריאות הבאות:

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

הקריאות האלה תמיד יחזירו את אותו ערך למכונה של האפליקציה, בהתאם למיקום שלה בקבוצת הבקרה או באחת מקבוצות הווריאנטים החדשים של המודעות, אלא אם בוצעו שינויים במסוף Firebase שאוחזרו והופעלו בקריאות הקודמות.




שלב 2: מגדירים בדיקת A/B במסוף Firebase שלב 4: מפעילים את בדיקת ה-A/B ובודקים את תוצאות הבדיקה