Rozpocznij

Pakiet SDK User Messaging Platform (UMP) od Google to narzędzie do ochrony prywatności i przesyłania wiadomości, ułatwiają zarządzanie wyborami dotyczącymi prywatności. Więcej informacji: Prywatność i informacje wiadomości.

Tworzenie typu wiadomości

Utwórz wiadomości dla użytkowników za pomocą jednej z tych metod: Dostępne typy wiadomości dla użytkowników w sekcji Prywatność na karcie „Wiadomości” Ad Manager koncie. Pakiet UMP SDK próbuje wyświetlić wiadomość dotycząca ochrony prywatności utworzona na podstawie Ad Manager identyfikatora aplikacji ustawione w projekcie.

Więcej informacji: Prywatność i wyświetlanie wiadomości

Importowanie pakietu SDK

CocoaPods (preferowane)

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

pod 'GoogleUserMessagingPlatform'

Następnie uruchom to polecenie:

pod install --repo-update

Jeśli dopiero zaczynasz korzystać z CocoaPods, przeczytaj artykuł Korzystanie z tej usługi. CocoaPods. tworzenia i używania plików Podfiles.

Menedżer pakietów Swift

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

  1. Zainstaluj w Xcode pakiet UMP SDK Swift. W tym celu przejdź na stronę Plik > Dodaj pakiety...

  2. W wyświetlonym oknie wyszukaj pakiet UMP SDK Swift na GitHubie. repozytorium:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Wybierz wersję pakietu UMP SDK Swift, którego chcesz użyć. Nowe zalecamy korzystanie z wersji do następnej głównej wersji.

Xcode rozwiązuje zależności pakietów i pobiera je do w tle. Więcej informacji o dodawaniu zależności pakietów znajdziesz w dokumencie Apple .

Pobieranie ręczne

Innym sposobem importowania pakietu SDK jest zrobienie tego ręcznie.

Pobierz pakiet SDK

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

Następnie możesz dodać tę platformę do dowolnego pliku, używając:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Dodaj identyfikator aplikacji

Identyfikator aplikacji znajdziesz w Interfejs Ad Managera. Dodaj dokument tożsamości do Info.plist z następującym fragmentem kodu:

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy</string>

Informacje o zgodzie użytkownika należy wysyłać w każdej aplikacji za pomocą funkcji requestConsentInfoUpdateWithParameters:completionHandler:. To żądanie sprawdza następujące:

  • Określ, czy wymagana jest zgoda. Zgoda jest np. wymagana w przypadku za pierwszym razem lub wygasła poprzednia decyzja.
  • Określ, czy wymagany jest punkt wejścia opcji prywatności. Niektóre wiadomości dotyczące ochrony prywatności będzie wymagać, aby aplikacje zezwalały użytkownikom na modyfikowanie ich opcji prywatności w dowolnym momencie.

Oto przykład, jak sprawdzić stan elementu UIViewController w Metoda 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 privacy message 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 privacy message form.
          }];
}

W razie potrzeby wczytaj i wyświetl formularz wiadomości dotyczącej ochrony prywatności

Po uzyskaniu najbardziej aktualnego stanu zgody zadzwoń pod numer loadAndPresentIfRequiredFromViewController:completionHandler: aby wczytać wszystkie formularze wymagane do uzyskiwania zgody użytkowników. Po wczytaniu formularze pojawią się 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 musisz wykonać jakieś działania po dokonaniu wyboru lub odrzuceniu go przez użytkownika umieść tę logikę w elemencie completion handler dla swojego formularza.

Opcje prywatności

Niektóre formularze wiadomości dotyczących ochrony prywatności są przedstawiane z prywatności renderowanej przez wydawcę. pozwala użytkownikom zarządzać ich opcjami prywatności w każdej chwili. Aby dowiedzieć się, jaki komunikat widzą użytkownicy, korzystając z opcji prywatności punktu wejścia, patrz Dostępne typy wiadomości dla użytkowników.

Aby wdrożyć punkt wejścia opcji prywatności, wykonaj te czynności:

  1. Zaznacz UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus.
  2. Jeśli punkt wejścia opcji prywatności to dodaj widoczny i interaktywny element interfejsu aplikacji.
  3. Aktywuj formularz opcji prywatności za pomocą polecenia presentPrivacyOptionsFormFromViewController:completionHandler:

Oto przykładowy kod, który ilustruje te kroki:

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.
                                  }
                                }];
}

Wyślij żądanie

Zanim wyślesz prośbę o reklamy w aplikacji, sprawdź, czy masz jej zgodę od użytkownika za pomocą funkcji UMPConsentInformation.sharedInstance.canRequestAds. Dostępne są 2 które sprawdzić podczas uzyskiwania zgody użytkowników:

  • Po uzyskaniu zgody użytkownika w bieżącej sesji.
  • Zaraz po nawiązaniu połączenia z firmą requestConsentInfoUpdateWithParameters:completionHandler:. Możliwe, że w poprzedniej sesji użytkownik wyraził zgodę. Jako opóźnienie zgodnie ze sprawdzoną metodą, nie czekaj na zakończenie połączenia, ponieważ będzie można ładowanie reklam od razu po uruchomieniu aplikacji.

Jeśli w trakcie procesu uzyskiwania zgody użytkowników wystąpi błąd, żądania reklam. Pakiet UMP SDK używa stanu zgody z poprzedniej wersji .

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...];
  });
}

Testowanie

Jeśli chcesz przetestować integrację w aplikacji w trakcie jej tworzenia, postępuj zgodnie z instrukcjami te kroki, by automatycznie zarejestrować urządzenie testowe. Pamiętaj, aby usunąć który będzie ustawiać te identyfikatory urządzeń testowych przed opublikowaniem aplikacji.

  1. Zadzwoń pod numer requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Sprawdź, czy w danych wyjściowych dziennika znajduje się komunikat podobny do poniższego przykładu, który pokazuje identyfikator Twojego urządzenia i jak dodać je 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 swój kod, aby połączenia UMPDebugSettings().testDeviceIdentifiers i przekaż 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ś użycie lokalizacji geograficznej

Pakiet UMP SDK umożliwia przetestowanie działania aplikacji w taki sposób, jakby urządzenie przebywających w Europejskim Obszarze Gospodarczym lub Wielkiej Brytanii za pomocą 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 SDK UMP pomocne może być zresetowanie pliku pakietu SDK, co pozwala symulować pierwszą instalację u użytkownika. Pakiet SDK udostępnia metodę reset .

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

Przykłady w GitHubie

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