Pierwsze kroki

Zgodnie z polityką Google w zakresie zgody użytkownika z UE musisz udzielać odpowiednich informacji użytkownikom z Europejskiego Obszaru Gospodarczego (EOG) i Wielkiej Brytanii oraz uzyskać ich zgodę na stosowanie plików cookie lub innych środków do lokalnego przechowywania danych, jeśli wymaga tego prawo, a także na wykorzystywanie danych osobowych (takich jak AdID) do wyświetlania reklam. Polityka ta odzwierciedla wymagania UE zawarte w dyrektywie o prywatności i łączności elektronicznej oraz w Ogólnym rozporządzeniu o ochronie danych (RODO).

Aby pomóc wydawcom w wypełnieniu obowiązków, jakie nakłada na nich ta polityka, Google oferuje pakiet SDK User Messaging Platform (UMP). Zaktualizowaliśmy pakiet SDK UMP, by obsługiwał najnowsze standardy IAB. Ze wszystkich tych konfiguracji można teraz wygodnie korzystać AdMob w sekcji Prywatność i wyświetlanie wiadomości.

Wymagania wstępne

Tworzenie typu wiadomości

Utwórz wiadomości dla użytkowników za pomocą dostępnych typów wiadomości dla użytkowników na karcie Prywatność i wyświetlanie wiadomości na swoim koncieAdMob . Pakiet UMP SDK próbuje wyświetlić komunikat dla użytkownika utworzony na podstawie AdMob identyfikatora aplikacji ustawionego w projekcie. Jeśli dla aplikacji nie jest skonfigurowany żaden komunikat, pakiet SDK zwraca błąd.

Więcej informacji znajdziesz w artykule Prywatność i wyświetlanie wiadomości.

Importowanie pakietu SDK

CocoaPods (preferowane)

Pakiet UMP SDK jest częścią zależności poda pakietu SDK do reklam mobilnych Google, który zaczyna się od pakietu SDK do reklam mobilnych Google w wersji 7.64.0.

Najprostszym sposobem na zaimportowanie pakietu SDK do projektu na iOS jest użycie CocoaPods. Otwórz plik Podfile projektu i dodaj ten wiersz do miejsca docelowego aplikacji:

pod 'Google-Mobile-Ads-SDK'

Następnie uruchom to polecenie:

pod install --repo-update

Jeśli dopiero zaczynasz korzystać z CocoaPods, zapoznaj się z sekcją Korzystanie z CocoaPods, aby dowiedzieć się, jak tworzyć i wykorzystywać pliki Podpliki.

Pobieranie ręczne

Inny sposób importowania pakietu SDK polega na ręcznym importowaniu.

Pobieranie pakietu SDK

Następnie przeciągnij platformę do projektu Xcode, zaznaczając w razie potrzeby opcję Kopiuj elementy.

Następnie możesz umieścić platformę w dowolnym potrzebnym pliku za pomocą:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Za pomocą requestConsentInfoUpdateWithParameters:completionHandler:należy prosić użytkownika o aktualizację informacji o zgodzie przy każdym uruchomieniu aplikacji. Określa to, czy użytkownik musi wyrazić zgodę, jeśli jeszcze tego nie zrobił lub czy zgoda wygasła.

Oto przykład, jak sprawdzić stan za pomocą obiektu UIViewController w metodzie viewDidLoad().

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Create a UMPRequestParameters object.
  let parameters = UMPRequestParameters()
  // Set tag for under age of consent. false means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = false

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
    [weak self] requestConsentError in
    guard let self else { return }

    if let consentError = requestConsentError {
      // Consent gathering failed.
      return print("Error: \(consentError.localizedDescription)")
    }

    // TODO: Load and present the consent form.
  }
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }

            // TODO: Load and present the consent form.
          }];
}

Wczytaj i w razie potrzeby wyświetl formularz zgody

Gdy otrzymasz najbardziej aktualny stan zgody, wywołajloadAndPresentIfRequiredFromViewController:completionHandler: klasyUMPConsentForm , aby wczytać formularz zgody. Jeśli wymagany jest stan zgody, pakiet SDK wczytuje formularz i natychmiast wyświetla go z przesłanych view controller. Po zamknięciu formularza wywoływane jest completion handler. Jeśli zgoda nie jest wymagana, obiekt completion handlerjest wywoływany natychmiast.

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Create a UMPRequestParameters object.
  let parameters = UMPRequestParameters()
  // Set tag for under age of consent. false means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = false

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
    [weak self] requestConsentError in
    guard let self else { return }

    if let consentError = requestConsentError {
      // Consent gathering failed.
      return print("Error: \(consentError.localizedDescription)")
    }

    UMPConsentForm.loadAndPresentIfRequired(from: self) {
      [weak self] loadAndPresentError in
      guard let self else { return }

      if let consentError = loadAndPresentError {
        // Consent gathering failed.
        return print("Error: \(consentError.localizedDescription)")
      }

      // Consent has been gathered.
    }
  }
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }

            __strong __typeof__(self) strongSelf = weakSelf;
            if (!strongSelf) {
              return;
            }

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  if (loadAndPresentError) {
                    // Consent gathering failed.
                    NSLog(@"Error: %@", loadAndPresentError.localizedDescription);
                    return;
                  }

                  // Consent has been gathered.
                }];
          }];
}

Jeśli po tym, jak użytkownik dokona wyboru lub zamknie formularz, musisz wykonać jakieś działania, które logiczne są completion handlerw formularzu.

Wyślij żądanie

Zanim poprosisz o wyświetlenie reklam w aplikacji, sprawdź, czy użytkownik uzyskał zgodę użytkownika za pomocą usługi UMPConsentInformation.sharedInstance.canRequestAds. Są 2 miejsca, które można sprawdzić podczas uzyskiwania zgody:

  1. Po uzyskaniu zgody użytkownika w bieżącej sesji.
  2. Zaraz po dołączeniu do requestConsentInfoUpdateWithParameters:completionHandler:. Możliwe, że użytkownik uzyskał zgodę w poprzedniej sesji. Sprawdzoną metodą dotyczącą opóźnienia jest nie czekanie na zakończenie wywołania zwrotnego, ponieważ pozwoli to rozpocząć ładowanie reklam od razu po uruchomieniu aplikacji.

Jeśli podczas uzyskiwania zgody użytkowników wystąpi błąd, nadal wysyłaj żądania reklam. Pakiet UMP SDK korzysta ze stanu zgody z poprzedniej sesji.

Swift

class ViewController: UIViewController {

  // Use a boolean to initialize the Google Mobile Ads SDK and load ads once.
  private var isMobileAdsStartCalled = false

  override func viewDidLoad() {
    super.viewDidLoad()

    // Create a UMPRequestParameters object.
    let parameters = UMPRequestParameters()
    // Set tag for under age of consent. false means users are not under age
    // of consent.
    parameters.tagForUnderAgeOfConsent = false

    // Request an update for the consent information.
    UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
      [weak self] requestConsentError in
      guard let self else { return }

      if let consentError = requestConsentError {
        // Consent gathering failed.
        return print("Error: \(consentError.localizedDescription)")
      }

      UMPConsentForm.loadAndPresentIfRequired(from: self) {
        [weak self] loadAndPresentError in
        guard let self else { return }

        if let consentError = loadAndPresentError {
          // Consent gathering failed.
          return print("Error: \(consentError.localizedDescription)")
        }

        // Consent has been gathered.
        if UMPConsentInformation.sharedInstance.canRequestAds {
          self.startGoogleMobileAdsSDK()
        }
      }
    }

    // Check if you can initialize the Google Mobile Ads SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if UMPConsentInformation.sharedInstance.canRequestAds {
      startGoogleMobileAdsSDK()
    }
  }

  private func startGoogleMobileAdsSDK() {
    DispatchQueue.main.async {
      guard !self.isMobileAdsStartCalled else { return }

      self.isMobileAdsStartCalled = true

      // Initialize the Google Mobile Ads SDK.
      GADMobileAds.sharedInstance().start()

      // TODO: Request an ad.
      // GADInterstitialAd.load(...)
    }
  }
}

Objective-C

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }
            __strong __typeof__(self) strongSelf = weakSelf;
            if (!strongSelf) {
              return;
            }

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  if (loadAndPresentError) {
                    // Consent gathering failed.
                    NSLog(@"Error: %@", loadAndPresentError.localizedDescription);
                    return;
                  }

                  // Consent has been gathered.
                  __strong __typeof__(self) strongSelf = weakSelf;
                  if (!strongSelf) {
                    return;
                  }

                  if (UMPConsentInformation.sharedInstance.canRequestAds) {
                    [strongSelf startGoogleMobileAdsSDKOnce];
                  }
                }];
          }];

  // Check if you can initialize the Google Mobile Ads SDK in parallel
  // while checking for new consent information. Consent obtained in
  // the previous session can be used to request ads.
  if (UMPConsentInformation.sharedInstance.canRequestAds) {
    [self startGoogleMobileAdsSDKOnce];
  }
}

- (void)startGoogleMobileAdsSDKOnce {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    // Initialize the Google Mobile Ads SDK.
    [GADMobileAds.sharedInstance startWithCompletionHandler:nil];

    // TODO: Request an ad.
    // [GADInterstitialAd loadWithAdUnitID...];
  });
}

Testowanie

Jeśli chcesz przetestować integrację z aplikacją w trakcie jej tworzenia, wykonaj podane niżej czynności, aby automatycznie zarejestrować urządzenie testowe.

  1. Zadzwoń pod numer requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Sprawdź, czy w wyniku logu nie widzisz komunikatu podobnego do poniższego, który zawiera identyfikator Twojego urządzenia i sposób dodawania go jako urządzenia testowego:

    <UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. Skopiuj identyfikator urządzenia testowego do schowka.

  4. Zmodyfikuj kod w taki sposób, aby wywoływał UMPDebugSettings().testDeviceIdentifiers i przekazywał listę identyfikatorów urządzeń testowych.

Swift

let parameters = UMPRequestParameters()
let debugSettings = UMPDebugSettings()
debugSettings.testDeviceIdentifiers = ["TEST-DEVICE-HASHED-ID"]
parameters.debugSettings = debugSettings
// Include the UMPRequestParameters in your consent request.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(
    with: parameters,
    completionHandler: { error in
      ...
    })

Objective-C

UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
UMPDebugSettings *debugSettings = [[UMPDebugSettings alloc] init];
debugSettings.testDeviceIdentifiers = @[ @"TEST-DEVICE-HASHED-ID" ];
parameters.debugSettings = debugSettings;
// Include the UMPRequestParameters in your consent request.
[UMPConsentInformation.sharedInstance
    requestConsentInfoUpdateWithParameters:parameters
                        completionHandler:^(NSError *_Nullable error){
                          ...
}];

Wymuś zastosowanie geograficzne

Pakiet UMP SDK umożliwia testowanie działania aplikacji tak, jakby urządzenie znajdowało się w Europejskim Obszarze Gospodarczym lub Wielkiej Brytanii w sieci the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Pamiętaj, że ustawienia debugowania działają tylko na urządzeniach testowych.

Swift

let parameters = UMPRequestParameters()
let debugSettings = UMPDebugSettings()
debugSettings.testDeviceIdentifiers = ["TEST-DEVICE-HASHED-ID"]
debugSettings.geography = .EEA
parameters.debugSettings = debugSettings
// Include the UMPRequestParameters in your consent request.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(
    with: parameters,
    completionHandler: { error in
      ...
    })

Objective-C

UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
UMPDebugSettings *debugSettings = [[UMPDebugSettings alloc] init];
debugSettings.testDeviceIdentifiers = @[ @"TEST-DEVICE-HASHED-ID" ];
debugSettings.geography = UMPDebugGeographyEEA;
parameters.debugSettings = debugSettings;
// Include the UMPRequestParameters in your consent request.
[UMPConsentInformation.sharedInstance
    requestConsentInfoUpdateWithParameters:parameters
                         completionHandler:^(NSError *_Nullable error){
                           ...
}];

Podczas testowania aplikacji za pomocą pakietu UMP SDK warto zresetować stan pakietu SDK, aby zasymulować proces pierwszej instalacji przez użytkownika. Metodę do wykonania tej czynności reset udostępnia pakiet SDK.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];