보상형 광고

보상형 광고는 사용자에게 상호작용에 대한 대가로 인앱 리워드에 대해 자세히 알아보세요. 이 가이드에는 AdMob을 Unity 앱에 삽입합니다.

고객 성공사례 읽어보기: 우수사례 1 우수사례 2를 참고하세요.

이 가이드에서는 Unity 앱에 보상형 광고를 통합하는 방법을 설명합니다.

기본 요건

항상 테스트 광고로 테스트

다음 샘플 코드에는 요청에 사용할 수 있는 광고 단위 ID가 포함되어 있습니다. 테스트 광고 테스트 광고를 반환하도록 특별히 구성된 경우 만들기 때문에 안전하게 사용할 수 있습니다.

하지만 AdMob 웹 인터페이스에서 자체 광고 단위를 만들었습니다 앱에서 사용할 ID를 확인하고 기기를 테스트로 명시적으로 구성하세요. 기기에서 있습니다.

Android

ca-app-pub-3940256099942544/5224354917

iOS

ca-app-pub-3940256099942544/1712485313

모바일 광고 SDK 초기화

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

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. 다음 보상형 광고 미리 로드

보상형 광고 로드

보상형 광고는Load() RewardedAd 클래스. 로드된 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) 콜백 확인

서버 측 확인에서 추가 데이터가 필요한 앱 콜백은 보상형 광고의 맞춤 데이터 기능을 사용해야 합니다. 보상형 광고 객체에 설정된 모든 문자열 값은 custom_data 쿼리 매개변수를 지정합니다. 맞춤 데이터 값이 설정되지 않은 경우 custom_data 쿼리 매개변수 값은 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();
    };
}

추가 리소스