Entrate pubblicitarie a livello di impressione

Seleziona la piattaforma: Android iOS Unity Android (Legacy)

Quando si verifica un'impressione, Google Mobile Ads SDK chiama il gestore di eventi paid con i dati sulle entrate associati. Implementando questo gestore, puoi utilizzare i dati per calcolare il lifetime value di un utente o inoltrarli a valle ad altri sistemi pertinenti.

Questa guida ha lo scopo di aiutarti a implementare l'acquisizione dei dati LTV nella tua app per iOS.

Prerequisiti

Implementare un gestore di eventi paid

Ogni formato dell'annuncio ha una paidEventHandler proprietà di tipo GADPaidEventHandler. Durante il ciclo di vita di un evento dell'annuncio, Google Mobile Ads SDK monitora gli eventi di impressione e richiama il gestore con un valore guadagnato.

Il seguente esempio gestisce gli eventi paid per un annuncio con premio:

Swift

rewardedAd?.paidEventHandler = { adValue in
  // TODO: Send the impression-level ad revenue information to your preferred
  // analytics server directly within this callback.

  // Extract the impression-level ad revenue data.
  let value = adValue.value
  let currencyCode = adValue.currencyCode
  let precision = adValue.precision

  print(
    "Ad paid event. Value: \(value) \(currencyCode), with precision: \(precision)."
  )
}

Objective-C

rewardedAd.paidEventHandler = ^(GADAdValue *_Nonnull adValue) {
  // TODO: Send the impression-level ad revenue information to your preferred
  // analytics server directly within this callback.

  // Extract the impression-level ad revenue data.
  NSDecimalNumber *value = adValue.value;
  NSString *currencyCode = adValue.currencyCode;
  GADAdValuePrecision precision = adValue.precision;

  NSLog(@"Ad paid event. Value: %@ %@, with precision: %ld.", value, currencyCode,
        (long)precision);
};

Identificare il nome di un'origine annuncio di eventi personalizzati

Per le origini annuncio di eventi personalizzati, adSourceName proprietà fornisce il nome dell'origine annuncio Custom event. Se utilizzi più eventi personalizzati, il nome dell'origine annuncio non è sufficientemente granulare per distinguere tra più eventi personalizzati. Per individuare un evento personalizzato specifico:

  1. Ottieni la proprietà adNetworkClassName.
  2. Imposta un nome di origine annuncio univoco.

Il seguente esempio imposta un nome di origine annuncio univoco per un evento personalizzato:

Swift

func uniqueAdSourceName(for loadedAdNetworkResponseInfo: AdNetworkResponseInfo) -> String {
  var adSourceName: String = loadedAdNetworkResponseInfo.adSourceName ?? ""
  if adSourceName == "Custom Event" {
    if loadedAdNetworkResponseInfo.adNetworkClassName
      == "MediationExample.SampleCustomEventSwift"
    {
      adSourceName = "Sample Ad Network (Custom Event)"
    }
  }
  return adSourceName
}

Objective-C

- (NSString *)uniqueAdSourceNameForAdNetworkResponseInfo:
    (GADAdNetworkResponseInfo *)loadedAdNetworkResponseInfo {
  NSString *adSourceName = loadedAdNetworkResponseInfo.adSourceName;
  if ([adSourceName isEqualToString:@"Custom Event"]) {
    if ([loadedAdNetworkResponseInfo.adNetworkClassName isEqualToString:@"SampleCustomEvent"]) {
      adSourceName = @"Sample Ad Network (Custom Event)";
    }
  }
  return adSourceName;
}

Per ulteriori informazioni sull'origine annuncio vincente, consulta Recuperare informazioni sulla risposta dell'annuncio.

Eseguire l'integrazione con i partner di attribuzione app (AAP)

Per informazioni dettagliate sull'inoltro dei dati sulle entrate pubblicitarie alle piattaforme di analisi, consulta la guida del partner:

SDK partner
Adjust
AppsFlyer
Singular
Tenjin

I seguenti esempi mostrano come inviare i dati sulle entrate a livello di impressione ai partner AAP utilizzando Google Mobile Ads SDK:

Adjust

Swift

func setPaidEventHandler(rewardAd: RewardedAd) {
  rewardAd.paidEventHandler = { adValue in
    guard let adRevenue = ADJAdRevenue(source: "admob_sdk") else { return }

    adRevenue.setRevenue(adValue.value.doubleValue, currency: adValue.currencyCode)
    if let adSourceName = rewardAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceName {
      adRevenue.setAdRevenueNetwork(adSourceName)
    }

    Adjust.trackAdRevenue(adRevenue)
  }
}

Objective-C

- (void)setPaidEventHandler:(GADRewardedAd *)rewardAd {
  NSString *adSourceName = rewardAd.responseInfo.loadedAdNetworkResponseInfo.adSourceName;

  rewardAd.paidEventHandler = ^(GADAdValue *_Nonnull adValue) {
    ADJAdRevenue *adRevenue = [[ADJAdRevenue alloc] initWithSource:@"admob_sdk"];
    if (!adRevenue) {
      return;
    }

    [adRevenue setRevenue:adValue.value.doubleValue currency:adValue.currencyCode];
    if (adSourceName) {
      [adRevenue setAdRevenueNetwork:adSourceName];
    }

    [Adjust trackAdRevenue:adRevenue];
  };
}

AppsFlyer

Swift

func setPaidEventHandler(rewardedAd: RewardedAd) {
  rewardedAd.paidEventHandler = { adValue in
    let adRevenueData = AFAdRevenueData(
      monetizationNetwork: "AdMob Mediation", mediationNetwork: MediationNetworkType.googleAdMob,
      currencyIso4217Code: adValue.currencyCode, eventRevenue: adValue.value)

    var additionalParameters = [:]
    additionalParameters[kAppsFlyerAdRevenueCountry] = "US"
    additionalParameters[kAppsFlyerAdRevenueAdUnit] = rewardedAd.adUnitID
    additionalParameters[kAppsFlyerAdRevenueAdType] = "Rewarded"

    AppsFlyerLib.shared().logAdRevenue(adRevenueData, additionalParameters: additionalParameters)
  }
}

Objective-C

- (void)setPaidEventHandler:(GADRewardedAd *)rewardedAd {
  NSString *adUnitID = rewardedAd.adUnitID;

  rewardedAd.paidEventHandler = ^(GADAdValue *_Nonnull adValue) {
    AFAdRevenueData *adRevenueData = [[AFAdRevenueData alloc]
        initWithMonetizationNetwork:@"AdMob Mediation"
                   mediationNetwork:AppsFlyerAdRevenueMediationNetworkTypeGoogleAdMob
                currencyIso4217Code:adValue.currencyCode
                       eventRevenue:adValue.value];

    NSMutableDictionary *additionalParameters = [[NSMutableDictionary alloc] init];
    additionalParameters[kAppsFlyerAdRevenueCountry] = @"US";
    additionalParameters[kAppsFlyerAdRevenueAdUnit] = adUnitID;
    additionalParameters[kAppsFlyerAdRevenueAdType] = @"Rewarded";

    [[AppsFlyerLib shared] logAdRevenue:adRevenueData additionalParameters:additionalParameters];
  };
}

Singular

Swift

func setPaidEventHandler(rewardedAd: RewardedAd) {
  rewardedAd.paidEventHandler = { adValue in
    // Extract revenue and currency from AdValue.
    let revenue = adValue.value.doubleValue
    let currency = adValue.currencyCode

    // Validate revenue and currency before sending.
    guard revenue > 0, !currency.isEmpty else {
      print(
        "Invalid ad revenue data: revenue = \(revenue), currency = \(String(describing: currency))"
      )
      return
    }

    // Create ad revenue data object.
    let data = SingularAdData(
      adPlatform: "AdMob",
      withCurrency: currency,
      withRevenue: NSNumber(value: revenue)
    )

    // Send to Singular.
    Singular.adRevenue(data)
    print("Ad revenue sent: \(revenue) \(currency)")
  }
}

Objective-C

- (void)setPaidEventHandler:(GADRewardedAd *)rewardedAd {
  rewardedAd.paidEventHandler = ^(GADAdValue *_Nonnull adValue) {
    // Extract revenue and currency from AdValue.
    double revenue = adValue.value.doubleValue;
    NSString *currency = adValue.currencyCode;

    // Validate revenue and currency before sending.
    if (revenue <= 0 || currency.length == 0) {
      NSLog(@"Invalid ad revenue data: revenue = %f, currency = %@", revenue, currency);
      return;
    }

    // Create ad revenue data object.
    SingularAdData *data =
        [[SingularAdData alloc] initWithAdPlatform:@"AdMob"
                                      withCurrency:currency
                                       withRevenue:[NSNumber numberWithDouble:revenue]];

    // Send to Singular.
    [Singular adRevenue:data];
    NSLog(@"Ad revenue sent: %f %@", revenue, currency);
  };
}

Tenjin

Swift

func setPaidEventHandler(rewardedAd: RewardedAd) {
  rewardedAd.paidEventHandler = { adValue in

    var jsonDict = [:]
    jsonDict["ad_unit_id"] = rewardedAd.adUnitID
    jsonDict["value_micros"] = adValue.value
    jsonDict["currency_code"] = adValue.currencyCode

    let responseInfo = rewardedAd.responseInfo
    if let responseIdentifier = responseInfo.responseIdentifier {
      jsonDict["response_id"] = responseIdentifier
    }
    if let adNetworkClassName = responseInfo.loadedAdNetworkResponseInfo?.adNetworkClassName {
      jsonDict["mediation_adapter_class_name"] = adNetworkClassName
    }

    do {
      let jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: [])
      let jsonString = String(data: jsonData, encoding: .utf8)
      TenjinSDK.adMobImpression(fromJSON: jsonString)
    } catch {
      print("Failed to log AdMob impression: \(error)")
    }
  }
}

Objective-C

- (void)setPaidEventHandler:(GADRewardedAd *)rewardedAd {
  NSString *adUnitID = rewardedAd.adUnitID;
  GADResponseInfo *responseInfo = rewardedAd.responseInfo;

  rewardedAd.paidEventHandler = ^(GADAdValue *_Nonnull adValue) {
    NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
    jsonDict[@"ad_unit_id"] = adUnitID;
    jsonDict[@"value_micros"] = adValue.value;
    jsonDict[@"currency_code"] = adValue.currencyCode;

    NSString *responseIdentifier = responseInfo.responseIdentifier;
    if (responseIdentifier) {
      jsonDict[@"response_id"] = responseIdentifier;
    }
    NSString *adNetworkClassName = responseInfo.loadedAdNetworkResponseInfo.adNetworkClassName;
    if (adNetworkClassName) {
      jsonDict[@"mediation_adapter_class_name"] = adNetworkClassName;
    }

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
    if (jsonData) {
      NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      [TenjinSDK adMobImpressionFromJSON:jsonString];
    } else {
      NSLog(@"Failed to log AdMob impression: %@", error);
    }
  };
}

Best practice per l'implementazione

  • Imposta il gestore immediatamente dopo aver creato o ottenuto l'accesso all'oggetto annuncio e sicuramente prima di mostrare l'annuncio. In questo modo, non perderai alcun callback di eventi paid.
  • Invia le informazioni sugli eventi paid al server di analisi che preferisci immediatamente al momento della chiamata del metodo paidEventHandler. In questo modo, non perderai accidentalmente alcun callback ed eviterai discrepanze nei dati.

GADAdValue

GADAdValue è una classe che rappresenta il valore monetario guadagnato per un annuncio, incluso il codice valuta del valore e il tipo di precisione codificato come segue.

GADAdValuePrecision Descrizione
GADAdValuePrecisionUnknown Un valore dell'annuncio sconosciuto. Questo valore viene restituito quando il pingback LTV è attivato, ma non sono disponibili dati sufficienti.
GADAdValuePrecisionEstimated Il valore di un annuncio stimato a partire da dati aggregati.
GADAdValuePrecisionPublisherProvided Un valore dell'annuncio fornito dal publisher, ad esempio i CPM manuali in un gruppo di mediazione.
GADAdValuePrecisionPrecise L'esatto valore pagato per questo annuncio.

Testare le impressioni dalle origini annuncio per l'asta

Dopo che si verifica un evento di entrate pubblicitarie a livello di impressione per un'origine annuncio per l'asta tramite una richiesta di test, ricevi solo i seguenti valori:

  • GADAdValuePrecisionUnknown: indica il tipo di precisione.
  • 0: indica il valore aggiunto dell'annuncio.
In precedenza, il tipo di precisione poteva essere un valore diverso da GADAdValuePrecisionUnknown e il valore dell'annuncio poteva essere maggiore di 0.

Per informazioni dettagliate sull'invio di una richiesta di annunci di test, consulta Attivare i dispositivi di test.