Wypróbuj

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 jest to wymagane prawnie. Musisz też uzyskać ich zgodę 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 UMP SDK, aby obsługiwał najnowsze standardy IAB. Wszystkimi tymi ustawieniami można teraz wygodnie zarządzać na stronie AdMob Prywatność i wyświetlanie wiadomości.

Wymagania wstępne

Tworzenie typu wiadomości

Utwórz wiadomości dla użytkowników, używając jednego z dostępnych typów wiadomości dla użytkowników na karcie Prywatność i wyświetlanie wiadomości na koncie AdMob UMP SDK próbuje wyświetlić wiadomość dla użytkownika utworzoną 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 artykuleo prywatności i przesyłaniu wiadomości.

Zaimportuj pakiet SDK

CocoaPods (preferowane)

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

Najprostszym sposobem zaimportowania pakietu SDK do projektu 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 nie masz doświadczenia z CocoaPods, przeczytaj artykuł o używaniu CocoaPods, aby dowiedzieć się, jak tworzyć i korzystać z podplików.

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 Kopiuj elementy.

Możesz potem dodać platformę do dowolnego pliku za pomocą:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

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

Oto przykład, jak sprawdzić stan z elementu 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 wyświetl formularz zgody, jeśli jest to wymagane

Ważne: te interfejsy API są zgodne z pakietem UMP SDK w wersji 2.1.0 lub nowszej.

Gdy otrzymasz najbardziej aktualny stan zgody, wywołajloadAndPresentIfRequiredFromViewController:completionHandler: na zajęciachUMPConsentForm , aby wczytać formularz zgody. Jeśli stan zgody jest wymagany, pakiet SDK wczytuje formularz i od razu go wyświetla z przesłanych view controller. Formularz completion handler jest wywoływany po zamknięciu formularza. Jeśli zgoda nie jest wymagana, completion handler jest 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 dokonaniu wyboru przez użytkownika lub odrzuceniu formularza musisz wykonać jakieś działanie, przenieś tę logikę do completion handlerformularza.

Wyślij żądanie

Zanim poprosisz o wyświetlenie reklam w aplikacji, sprawdź, czy masz zgodę użytkownika korzystającego z usługi UMPConsentInformation.sharedInstance.canRequestAds. Zdobywanie zgody można sprawdzić w 2 miejscach:

  1. Gdy w bieżącej sesji uzyskasz zgodę użytkownika.
  2. Zaraz po rozmowie telefonicznej z firmą requestConsentInfoUpdateWithParameters:completionHandler:. Możliwe, że zgoda została uzyskana w poprzedniej sesji. Ze względu na czas oczekiwania zalecamy 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 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) {
    [self startGoogleMobileAdsSDK];
  }
}

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

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

Opcje prywatności

Niektóre formularze zgody wymagają od użytkownika zmodyfikowania jej zgody w dowolnym momencie. W razie potrzeby postępuj zgodnie z instrukcjami poniżej, aby zaimplementować przycisk opcji prywatności.

W tym celu:

  1. Zaimplementuj element interfejsu, np. przycisk na stronie ustawień aplikacji, który może powodować wyświetlanie formularza opcji prywatności.
  2. Po loadAndPresentIfRequiredFromViewController:completionHandler: zakończeniu zaznaczprivacyOptionsRequirementStatus , aby określić, czy wyświetlić element interfejsu, który może wyświetlać formularz opcji prywatności.
  3. Gdy użytkownik wejdzie w interakcję z elementem interfejsu, wywołajpresentPrivacyOptionsFormFromViewController:completionHandler: , aby wyświetlić formularz. Dzięki temu będzie mógł w dowolnym momencie zaktualizować swoje opcje prywatności.

Z przykładu poniżej dowiesz się, jak zaprezentować formularz opcji prywatności z poziomu UIBarButtonItem.

Swift

@IBOutlet weak var privacySettingsButton: UIBarButtonItem!

var isPrivacyOptionsRequired: Bool {
  return UMPConsentInformation.shared.privacyOptionsRequirementStatus == .required
}

override func viewDidLoad() {
  // ...

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
    // ...

    UMPConsentForm.loadAndPresentIfRequired(from: self) {
      //...

      // Consent has been gathered.

      // Show the button if privacy options are required.
      self.privacySettingsButton.isEnabled = isPrivacyOptionsRequired
    }
  }
  // ...
}

// Present the privacy options form when a user interacts with the
// privacy settings button.
@IBAction func privacySettingsTapped(_ sender: UIBarButtonItem) {
  UMPConsentForm.presentPrivacyOptionsForm(from: self) {
    [weak self] formError in
    guard let self, let formError else { return }

    // Handle the error.
  }
}

Objective-C

@interface ViewController ()
@property(weak, nonatomic) IBOutlet UIBarButtonItem *privacySettingsButton;
@end

- (BOOL)isPrivacyOptionsRequired {
  return UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus ==
         UMPPrivacyOptionsRequirementStatusRequired;
}

- (void)viewDidLoad {
  // ...

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            // ...

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  // ...

                  // Consent has been gathered.

                  // Show the button if privacy options are required.
                  strongSelf.privacySettingsButton.enabled = isPrivacyOptionsRequired;
                }];
          }];
}

// Present the privacy options form when a user interacts with your
// privacy settings button.
- (IBAction)privacySettingsTapped:(UIBarButtonItem *)sender {
  [UMPConsentForm presentPrivacyOptionsFormFromViewController:self
                                completionHandler:^(NSError *_Nullable formError) {
                                  if (formError) {
                                    // Handle the error.
                                  }
                                }];
}

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. Poszukaj w dzienniku komunikatu podobnego do tego poniżej, który zawiera identyfikator Twojego urządzenia i informację, jak dodać go jako urządzenie testowe:

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

  4. Zmień kod w taki sposób, aby wywoływanie UMPDebugSettings().testDeviceIdentifiers i przekazywanie listy 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 przez parametr 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ć jego stan, aby zasymulować proces pierwszej instalacji. Aby to zrobić, pakiet SDK udostępnia reset metodę.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

Przykłady na GitHubie

Przykłady integracji pakietu UMP SDK: Swift | Objective-C