보상형 광고

보상형 광고는 사용자에게 상호작용에 대한 대가로 인앱 리워드를 제공하는 광고입니다. 이 가이드에는 AdMob에서 Unity 앱에 보상형 광고를 통합하는 방법이 나와 있습니다.

고객 성공사례인 우수사례 1우수사례 2를 읽어보세요.

이 가이드에는 보상형 광고를 Unity 앱에 통합하는 방법이 나와 있습니다.

기본 요건

항상 테스트 광고로 테스트

다음 샘플 코드에는 테스트 광고를 요청하는 데 사용할 수 있는 광고 단위 ID가 포함되어 있습니다. 이 ID는 모든 요청에 대해 프로덕션 광고가 아닌 테스트 광고를 반환하도록 구성되어서 안전하게 사용할 수 있습니다.

그러나AdMob 웹 인터페이스에 앱을 등록하고 앱에서 사용할 광고 단위 ID를 직접 만든 후에는 개발 중에 명시적으로 기기를 테스트 기기로 구성해야 합니다.

Android

ca-app-pub-3940256099942544/5224354917

iOS

ca-app-pub-3940256099942544/1712485313

모바일 광고 SDK 초기화

광고를 로드하기 전에 MobileAds.Initialize()를 호출하여 앱에서 모바일 광고 SDK를 초기화하도록 합니다. 이 작업은 앱 실행 시 한 번만 처리하면 됩니다.

using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}

미디에이션을 사용하는 경우 광고를 로드하기 전에 콜백이 발생할 때까지 기다려야 모든 미디에이션 어댑터가 초기화됩니다.

구현

보상형 광고를 통합하는 기본 단계는 다음과 같습니다.

  1. 보상형 광고 로드
  2. [선택사항] 서버 측 확인 (SSV) 콜백 확인
  3. 리워드 콜백으로 보상형 광고 표시
  4. 보상형 광고 이벤트 수신
  5. 보상형 광고 정리
  6. 다음 보상형 광고 미리 로드

보상형 광고 로드

보상형 광고는 RewardedAd 클래스의 정적 Load() 메서드를 이용해 로드됩니다. 로드된 RewardedAd 객체는 완료 핸들러의 매개변수로 제공됩니다. 아래는 RewardedAd를 로드하는 방법의 예입니다.


  // These ad units are configured to always serve test ads.
#if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
#else
  private string _adUnitId = "unused";
#endif

  private RewardedAd _rewardedAd;

  /// <summary>
  /// Loads the rewarded ad.
  /// </summary>
  public void LoadRewardedAd()
  {
      // Clean up the old ad before loading a new one.
      if (_rewardedAd != null)
      {
            _rewardedAd.Destroy();
            _rewardedAd = null;
      }

      Debug.Log("Loading the rewarded ad.");

      // create our request used to load the ad.
      var adRequest = new AdRequest();

      // send the request to load the ad.
      RewardedAd.Load(_adUnitId, adRequest,
          (RewardedAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("Rewarded ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Rewarded ad loaded with response : "
                        + ad.GetResponseInfo());

              _rewardedAd = ad;
          });
  }

[선택사항] 서버 측 확인 (SSV) 콜백 확인

서버 측 확인 콜백에서 추가 데이터가 필요한 앱은 보상형 광고의 맞춤 데이터 기능을 사용해야 합니다. 보상형 광고 객체에 설정된 모든 문자열 값은 SSV 콜백의 custom_data 쿼리 매개변수에 전달됩니다. 맞춤 데이터 값이 설정되지 않은 경우 custom_data 쿼리 매개변수 값은 SSV 콜백에 표시되지 않습니다.

다음 코드 샘플은 보상형 광고가 로드된 후 SSV 옵션을 설정하는 방법을 보여줍니다.

// send the request to load the ad.
RewardedAd.Load(_adUnitId, adRequest, (RewardedAd ad, LoadAdError error) =>
{
    // If the operation failed, an error is returned.
    if (error != null || ad == null)
    {
        Debug.LogError("Rewarded ad failed to load an ad with error : " + error);
        return;
    }

    // If the operation completed successfully, no error is returned.
    Debug.Log("Rewarded ad loaded with response : " + ad.GetResponseInfo());

    // Create and pass the SSV options to the rewarded ad.
    var options = new ServerSideVerificationOptions
                          .Builder()
                          .SetCustomData("SAMPLE_CUSTOM_DATA_STRING")
                          .Build()
    ad.SetServerSideVerificationOptions(options);

});

광고를 게재하기 전에 맞춤 보상 문자열을 설정해야 합니다.

리워드 콜백으로 보상형 광고 표시

광고를 표시할 때 사용자의 보상을 처리할 콜백을 제공해야 합니다. 광고는 로드당 한 번만 게재될 수 있습니다. CanShowAd() 메서드를 사용하여 광고를 게재할 준비가 되었는지 확인하세요.

다음 코드는 보상형 광고를 게재하기 위한 최적의 메서드를 나타냅니다.

public void ShowRewardedAd()
{
    const string rewardMsg =
        "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

    if (rewardedAd != null && rewardedAd.CanShowAd())
    {
        rewardedAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}

보상형 광고 이벤트 수신

광고의 작동 방식을 추가로 맞춤설정하려는 경우 광고의 수명 주기에서 여러 이벤트(예: 열기, 닫기)에 연결하면 됩니다. 아래와 같이 대리자를 등록하여 이러한 이벤트를 수신합니다.

private void RegisterEventHandlers(RewardedAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded ad was clicked.");
    };
    // Raised when an ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);
    };
}

보상형 광고 정리

RewardedAd 지정이 끝나면 참조를 삭제하기 전에 Destroy() 메서드를 호출해야 합니다.

_rewardedAd.Destroy();

이렇게 하면 플러그인이 객체를 더 이상 사용하지 않으며 객체가 점유하는 메모리를 회수할 수 있음을 알립니다. 이 메서드를 호출하지 않으면 메모리 누수가 발생합니다.

다음 보상형 광고 미리 로드

RewardedAd는 일회용 객체입니다. 즉, 보상형 광고가 표시된 후에는 이 객체를 다시 사용할 수 없습니다. 다른 보상형 광고를 요청하려면 새 RewardedAd 객체를 만들어야 합니다.

다음 노출 기회에 보상형 광고가 게재되도록 OnAdFullScreenContentClosed 또는 OnAdFullScreenContentFailed 광고 이벤트가 발생한 후에 보상형 광고를 미리 로드합니다.

private void RegisterReloadHandler(RewardedAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded Ad full screen content closed.");

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
}

추가 리소스