3단계: 앱 코드에서 Remote Config 매개변수 값 처리
소개: Firebase를 사용하여 AdMob 광고 게재빈도 최적화 |
1단계: AdMob를 사용하여 테스트할 새 광고 단위 대안 만들기 |
2단계: Firebase Console에서 A/B 테스트 설정 |
3단계: 앱 코드에서 Remote Config 매개변수 값 처리 |
4단계: Firebase Console에서 A/B 테스트 시작 및 테스트 결과 검토 |
5단계: 새 광고 형식 출시 여부 결정 |
마지막 단계가 끝나면 Remote Config 매개변수(INTERSTITIAL_AD_KEY
)가 생성됩니다. 이 단계에서는 이 매개변수의 값을 기준으로 앱에 표시할 항목에 대한 논리를 앱 코드에 추가합니다.
필수 SDK 추가
애플리케이션 코드에서 Remote Config를 사용하려면 먼저 Remote Config SDK와 Google Analytics용 Firebase SDK를 모두 프로젝트 빌드 파일에 추가합니다.
Swift
Podfile에서 다음 포드를 추가하고 설치합니다.
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
Objective-C
Podfile에서 다음 포드를 추가하고 설치합니다.
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
Android
build.gradle
파일에 다음 라이브러리 종속 항목을 추가합니다.
implementation 'com.google.android.gms:play-services-ads:24.2.0'
implementation 'com.google.firebase:firebase-analytics:22.4.0'
implementation 'com.google.firebase:firebase-config:22.1.0'
Unity
Firebase Unity SDK를 다운로드하고 설치한 후 다음 Unity 패키지를 프로젝트에 추가합니다.
FirebaseAnalytics.unitypackage
FirebaseRemoteConfig.unitypackage
Remote Config 인스턴스 구성
Remote Config 매개변수 값을 사용하려면 클라이언트 앱 인스턴스에 대해 새 값을 가져오도록 Remote Config 인스턴스를 구성합니다.
이 예에서 Remote Config는 1시간마다 새 매개변수 값을 확인하도록 구성되어 있습니다.
Swift
remoteConfig = RemoteConfig.remoteConfig()
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 3600
remoteConfig.configSettings = settings
Objective-C
self.remoteConfig = [FIRRemoteConfig remoteConfig];
FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] init];
remoteConfigSettings.minimumFetchInterval = 3600;
self.remoteConfig.configSettings = remoteConfigSettings;
Java
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(3600)
.build();
mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
Kotlin
remoteConfig = Firebase.remoteConfig
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = 3600
}
remoteConfig.setConfigSettingsAsync(configSettings)
Unity
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 값을 미리 가져와야 하므로, 앱의 로딩 단계에서 가능하면 빨리 이 호출을 실행해야 합니다.
Swift
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()
}
Objective-C
[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];
}];
Java
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();
}
});
Kotlin
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()
}
Unity
remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted) {
Debug.LogWarning("Config params failed to update");
} else {
Debug.Log("Config params updated: " + task.Result);
}
LoadAdUnit();
});
이제 이 튜토리얼의 앞부분에서 A/B 테스트를 설정할 때 생성된 Remote Config 매개변수를 앱에서 처리할 준비가 되었습니다.
Remote Config 매개변수 값 사용
loadAdUnit()
함수에서 미리 가져온 Remote Config 값을 사용하여 이 앱 인스턴스에 표시할 광고 게재빈도 대안을 확인합니다.
Swift
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.
Objective-C
- (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;
}];
}
Java
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;
}
});
}
Kotlin
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
}
})
}
Unity
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 매개변수의 값을 확인해야 하는 다른 영역이 있습니다. 예를 들어 사용자 현재 광고 보기를 마친 후 광고를 새로고침할지 여부를 결정할 수 있습니다.
실험을 종료하거나 새로 만들기로 결정하는 경우와 같이 매개변수 값 변화를 가져오기 위해서는 먼저 가져오기 및 활성화 호출을 수행해야 합니다.
이후 항상 다음 호출을 사용하여 매개변수의 값을 확인할 수 있습니다.
Swift
remoteConfig["INTERSTITIAL_AD_KEY"].stringValue
Objective-C
self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;
Java
mFirebaseRemoteConfig.getString(INTERSTITIAL_AD_KEY)
Kotlin
remoteConfig.getString(INTERSTITIAL_AD_KEY)
Unity
remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue
이전 호출에서 가져오고 활성화한 변경사항이 Firebase Console에서 적용되지 않은 경우를 제외하고 이러한 호출은 통제 그룹에 속했거나 새 광고 대안 그룹 중 하나에 속했든지에 관계없이 앱 인스턴스에 대해 항상 동일한 값을 반환합니다.
Firebase Console에서 A/B 테스트 설정 2단계: 4단계: A/B 테스트 시작 및 테스트 결과 검토