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 konfiguracjami możesz teraz wygodnie zarządzać na stronie AdMob prywatności i przesyłania wiadomości.

Wymagania wstępne

Tworzenie typu wiadomości

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

Więcej informacji znajdziesz w artykule Informacje o prywatności i przesyłaniu wiadomości.

Importowanie pakietu SDK

CocoaPods (preferowane)

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

pod 'GoogleUserMessagingPlatform'

Następnie uruchom to polecenie:

pod install --repo-update

Jeśli nie masz doświadczenia w korzystaniu z CocoaPods, przeczytaj sekcję o używaniu CocoaPods, aby dowiedzieć się, jak tworzyć i wykorzystywać pliki Podpliki.

Menedżer pakietów Swift

Pakiet UMP SDK obsługuje też menedżera pakietów Swift. Wykonaj te czynności, aby zaimportować pakiet Swift.

  1. Zainstaluj w Xcode pakiet Swift SDK UMP, klikając Plik > Dodaj pakiety...

  2. W wyświetlonym komunikacie wyszukaj na GitHubie repozytorium pakietu Swift SDK UMP:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Wybierz wersję pakietu UMP SDK Swift, której chcesz użyć. W przypadku nowych projektów zalecamy używanie trybu Up to Next Major Version (Do następnej wersji głównej).

Xcode następnie rozstrzygnie zależności pakietów i pobierze je w tle. Więcej informacji o dodawaniu zależności pakietów znajdziesz w artykule Apple.

Pobieranie ręczne

Innym sposobem importowania pakietu SDK jest ręczne.

Pobierz pakiet SDK

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

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

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Po każdym uruchomieniu aplikacji musisz prosić użytkownika o aktualizację informacji o zgodzie użytkownika za pomocą funkcji requestConsentInfoUpdateWithParameters:completionHandler:. Pozwala to określić, czy użytkownik musi wyrazić zgodę, jeśli jeszcze tego nie zrobił, czy też wygasła.

Oto przykład, jak sprawdzić stan z zasobu UIViewController w metodzie viewDidLoad().

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
    [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];

  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          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

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

Gdy otrzymasz najbardziej aktualny stan zgody, zadzwońloadAndPresentIfRequiredFromViewController:completionHandler: naUMPConsentForm zajęcia, aby wczytać formularz zgody. Jeśli stan zgody jest wymagany, pakiet SDK wczytuje formularz i od razu wyświetla go z przesłanych view controller. Po zamknięciu formularza completion handler jest wywoływany . Jeśli zgoda nie jest wymagana, proces completion handler od razu .

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
    [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];

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          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 zamknięciu formularza musisz wykonać jakieś działanie, zastosuj tę logikę w completion handlerformularzu.

Wyślij żądanie

Zanim poprosisz o reklamy w aplikacji, sprawdź, czy masz zgodę użytkownika korzystającego z usługi UMPConsentInformation.sharedInstance.canRequestAds. Zgodę należy sprawdzić w 2 miejscach:

  1. Gdy w bieżącej sesji uzyskasz zgodę użytkowników.
  2. Zaraz po rozmowie telefonicznej z firmą requestConsentInfoUpdateWithParameters:completionHandler:. Możliwe, że zgoda została udzielona w poprzedniej sesji. Zalecamy, aby nie czekać na zakończenie wywołania zwrotnego, ponieważ pozwoli to rozpocząć ładowanie reklam jak najszybciej po uruchomieniu aplikacji.

Jeśli podczas uzyskiwania zgody użytkowników wystąpi błąd, nadal próbuj wysłać żądania reklam. Pakiet UMP SDK używa 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()

    // Request an update for the consent information.
    UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
      [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];

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          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 wprowadzenia zmian w dowolnym momencie. Aby w razie potrzeby zaimplementować przycisk opcji prywatności, postępuj zgodnie z poniższymi instrukcjami.

W tym celu:

  1. Zaimplementuj element interfejsu, np. przycisk na stronie ustawień aplikacji, który może uruchamiać formularz opcji prywatności.
  2. Gdy loadAndPresentIfRequiredFromViewController:completionHandler: to się zakończy, 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.

Przykład poniżej pokazuje, jak przedstawić formularz opcji prywatności z UIBarButtonItem.

Swift

@IBOutlet weak var privacySettingsButton: UIBarButtonItem!

var isPrivacyOptionsRequired: Bool {
  return UMPConsentInformation.sharedInstance.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 te czynności, aby automatycznie zarejestrować urządzenie testowe. Pamiętaj, aby przed opublikowaniem aplikacji usunąć kod, który ustawia te identyfikatory urządzeń testowych.

  1. Zadzwoń pod numer requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Sprawdź, czy w danych wyjściowych logu nie pojawia się komunikat podobny do tego przykładowego poniżej, który zawiera identyfikator urządzenia i informuje, 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. Zmodyfikuj kod tak, 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ś ustawienie geograficzne

Pakiet UMP SDK umożliwia przetestowanie działania aplikacji tak, jakby urządzenie znajdowało się w Europejskim Obszarze Gospodarczym lub Wielkiej Brytanii w ramach usługi 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 tego pakietu, aby zasymulować proces pierwszej instalacji przez użytkownika. Pakiet SDK udostępnia reset metodę pozwalającą to zrobić.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

Przykłady w GitHubie

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