开始使用

Google User Messaging Platform (UMP) SDK 是一款隐私权和消息工具,可帮助您管理隐私选项。如需了解详情,请参阅“隐私权和消息”页面简介。 您可以在 Objective-CSwift UMP 示例应用中查看使用 UMP SDK 的有效 IMA 实现。

创建消息类型

在 Ad Manager 账号的隐私权和消息标签页下,使用其中一种可用的用户消息类型创建用户消息。UMP SDK 会尝试显示根据您在项目中设置的互动式媒体广告应用 ID 创建的隐私权消息。

如需了解详情,请参阅隐私权和消息简介

导入 SDK

UMP SDK 未作为 IMA SDK 的依赖项包含在内,因此您必须自行明确添加该 SDK。

CocoaPods(首选)

如要将该 SDK 导入 iOS 项目,最简单的方法就是使用 CocoaPods。请打开项目的 Podfile 并将下面这行代码添加到应用的目标中:

pod 'GoogleUserMessagingPlatform'

然后运行以下命令:

pod install --repo-update

如果您刚开始接触 CocoaPods,请参阅如何使用 CocoaPods,详细了解如何创建和使用 Podfile。

Swift Package Manager

UMP SDK 还支持 Swift Package Manager。请按照以下步骤导入 Swift 软件包。

  1. 在 Xcode 中,依次前往 File(文件)> Add Packages(添加软件包),安装 UMP SDK Swift 软件包。

  2. 在显示的提示中,搜索 UMP SDK Swift 软件包的 GitHub 代码库:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. 选择要使用的 UMP SDK Swift 软件包版本。对于新项目,我们建议使用 Up to Next Major Version

然后,Xcode 会解析您的软件包依赖项,并在后台下载它们。如需详细了解如何添加软件包依赖项,请参阅 Apple 的文章

添加应用 ID

您可以在 Ad Manager 界面中找到您的应用 ID。 使用以下代码段将 ID 添加到 Info.plist

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

如需征求用户同意,请完成以下步骤:

  1. 请求获取最新的用户意见征求信息。
  2. 根据需要加载并显示用户意见征求表单。

每次启动应用时,您都应使用 requestConsentInfoUpdateWithParameters:completionHandler: 请求更新用户的意见征求信息。此请求会检查以下内容:

  • 是否需要征得用户同意。例如,首次需要征得用户同意,或者之前的用户意见征求结果已过期。
  • 是否必须提供隐私设置选项入口点。某些隐私权消息要求应用允许用户随时修改其隐私选项。

根据需要加载和显示隐私权消息表单

收到最新的意见征求状态后,调用 loadAndPresentIfRequiredFromViewController:completionHandler: 以加载收集用户意见征求所需的所有表单。加载后,表单会立即显示。

以下代码演示了如何请求用户的最新意见征求信息。如有需要,该代码会加载并显示隐私权消息表单:

Swift


// Requesting an update to consent information should be called on every app launch.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
  requestConsentError in
  guard requestConsentError == nil else {
    return consentGatheringComplete(requestConsentError)
  }

  UMPConsentForm.loadAndPresentIfRequired(from: consentFormPresentationviewController) {
    loadAndPresentError in

    // Consent has been gathered.
    consentGatheringComplete(loadAndPresentError)
  }
}

Objective-C


// Requesting an update to consent information should be called on every app launch.
[UMPConsentInformation.sharedInstance
    requestConsentInfoUpdateWithParameters:parameters
                         completionHandler:^(NSError *_Nullable requestConsentError) {
                           if (requestConsentError) {
                             consentGatheringComplete(requestConsentError);
                           } else {
                             [UMPConsentForm
                                 loadAndPresentIfRequiredFromViewController:viewController
                                                          completionHandler:^(
                                                              NSError
                                                                  *_Nullable loadAndPresentError) {
                                                            // Consent has been gathered.
                                                            consentGatheringComplete(
                                                                loadAndPresentError);
                                                          }];
                           }
                         }];

隐私选项

某些隐私权消息表单会通过发布商呈现的隐私权选项入口点显示,以便用户随时管理其隐私权选项。如需详细了解您的用户会在隐私权选项入口点看到哪条消息,请参阅可用的用户消息类型

检查是否需要隐私设置选项入口点

调用 requestConsentInfoUpdateWithParameters:completionHandler: 后,请检查 UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus,以确定您的应用是否需要隐私选项入口点:

Swift


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

Objective-C


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

向应用添加可见元素

如果需要隐私权入口点,请向应用添加一个可见且可交互的界面元素,用于显示隐私权选项表单。如果不需要隐私权入口点,请将界面元素配置为不可见且不可互动。

Swift


self.privacySettingsButton.isEnabled = ConsentManager.shared.isPrivacyOptionsRequired

Objective-C


// Set up the privacy options button to show the UMP privacy form.
// Check ConsentInformation.getPrivacyOptionsRequirementStatus
// to see the button should be shown or hidden.
strongSelf.privacySettingsButton.hidden =
    !ConsentManager.sharedInstance.areGDPRConsentMessagesRequired;

显示隐私选项表单

当用户与您的元素互动时,显示隐私选项表单:

Swift


UMPConsentForm.presentPrivacyOptionsForm(
  from: viewController, completionHandler: completionHandler)

Objective-C


[UMPConsentForm presentPrivacyOptionsFormFromViewController:viewController
                                          completionHandler:completionHandler];

提出广告请求

在应用中请求展示广告之前,请检查您是否已使用 UMPConsentInformation.sharedInstance.canRequestAds 征得用户同意。在征求用户意见时,您可以检查以下两个位置:

  • 在当前会话中征得用户同意后。
  • 在调用 requestConsentInfoUpdateWithParameters:completionHandler: 后立即调用。系统可能已在上一会话中征得用户同意。延迟时间最佳实践:我们建议您不要等待回调完成,以便在应用启动后尽快开始加载广告。

如果在征求用户同意的过程中发生错误,您仍应检查自己是否可以请求展示广告。UMP SDK 会使用上一个会话中的意见征求状态。

以下代码会检查您是否可以在征求用户意见的过程中请求展示广告:

Swift


ConsentManager.shared.gatherConsent(from: self) { [weak self] consentError in
  guard let self else { return }

  if let consentError {
    // Consent gathering failed. This sample loads ads using
    // consent obtained in the previous session.
    print("Error: \(consentError.localizedDescription)")
  }
  // ...
}

Objective-C


  [ConsentManager.sharedInstance
      gatherConsentFromConsentPresentationViewController:self
                                consentGatheringComplete:^(NSError *_Nullable consentError) {
                                  if (consentError) {
                                    // Consent gathering failed.
                                    NSLog(@"Error: %@", consentError.localizedDescription);
                                  }

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

                                  // ...

                                  if (ConsentManager.sharedInstance.canRequestAds) {
                                    [strongSelf setupAdsLoader];
                                  }
                                }];

  // This sample attempts to load ads using consent obtained in the previous session.
  if (ConsentManager.sharedInstance.canRequestAds) {
    [self setupAdsLoader];
  }

  [self setUpContentPlayer];
}

- (IBAction)onPlayButtonTouch:(id)sender {
  [self requestAds];
  self.playButton.hidden = YES;
}

#pragma mark Content Player Setup

- (void)setUpContentPlayer {
  // Load AVPlayer with path to our content.
  NSURL *contentURL = [NSURL URLWithString:kTestAppContentUrl_MP4];
  self.contentPlayer = [AVPlayer playerWithURL:contentURL];

  // Create a player layer for the player.
  AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.contentPlayer];

  // Size, position, and display the AVPlayer.
  playerLayer.frame = self.videoView.layer.bounds;
  [self.videoView.layer addSublayer:playerLayer];

  // Set up our content playhead and contentComplete callback.
  self.contentPlayhead = [[IMAAVPlayerContentPlayhead alloc] initWithAVPlayer:self.contentPlayer];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(contentDidFinishPlaying:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:self.contentPlayer.currentItem];
}

#pragma mark SDK Setup

- (void)setupAdsLoader {
  self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:nil];
  self.adsLoader.delegate = self;
}

- (void)requestAds {
  // Create an ad display container for ad rendering.
  IMAAdDisplayContainer *adDisplayContainer =
      [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                          viewController:self
                                          companionSlots:nil];
  // Create an ad request with our ad tag, display container, and optional user context.
  IMAAdsRequest *request = [[IMAAdsRequest alloc] initWithAdTagUrl:kTestAppAdTagUrl
                                                adDisplayContainer:adDisplayContainer
                                                   contentPlayhead:self.contentPlayhead
                                                       userContext:nil];
  [self.adsLoader requestAdsWithRequest:request];
}

- (void)contentDidFinishPlaying:(NSNotification *)notification {
  // Make sure we don't call contentComplete as a result of an ad completing.
  if (notification.object == self.contentPlayer.currentItem) {
    [self.adsLoader contentComplete];
  }
}

#pragma mark AdsLoader Delegates

- (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData {
  // Grab the instance of the IMAAdsManager and set ourselves as the delegate.
  self.adsManager = adsLoadedData.adsManager;
  self.adsManager.delegate = self;
  // Create ads rendering settings to tell the SDK to use the in-app browser.
  IMAAdsRenderingSettings *adsRenderingSettings = [[IMAAdsRenderingSettings alloc] init];
  adsRenderingSettings.linkOpenerPresentingController = self;
  // Initialize the ads manager.
  [self.adsManager initializeWithAdsRenderingSettings:adsRenderingSettings];
}

- (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData {
  // Something went wrong loading ads. Log the error and play the content.
  NSLog(@"Error loading ads: %@", adErrorData.adError.message);
  [self.contentPlayer play];
}

#pragma mark AdsManager Delegates

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdEvent:(IMAAdEvent *)event {
  // When the SDK notified us that ads have been loaded, play them.
  if (event.type == kIMAAdEvent_LOADED) {
    [adsManager start];
  }
}

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdError:(IMAAdError *)error {
  // Something went wrong with the ads manager after ads were loaded. Log the error and play the
  // content.
  NSLog(@"AdsManager error: %@", error.message);
  [self.contentPlayer play];
}

- (void)adsManagerDidRequestContentPause:(IMAAdsManager *)adsManager {
  // The SDK is going to play ads, so pause the content.
  [self.contentPlayer pause];
}

- (void)adsManagerDidRequestContentResume:(IMAAdsManager *)adsManager {
  // The SDK is done playing ads (at least for now), so resume the content.
  [self.contentPlayer play];
}

@end

以下代码会在征得用户同意后设置 IMA DAI SDK:

Swift


private func requestAds() {
  // Create ad display container for ad rendering.
  let adDisplayContainer = IMAAdDisplayContainer(
    adContainer: videoView, viewController: self, companionSlots: nil)
  // Create an ad request with our ad tag, display container, and optional user context.
  let request = IMAAdsRequest(
    adTagUrl: ViewController.testAppAdTagURL,
    adDisplayContainer: adDisplayContainer,
    contentPlayhead: contentPlayhead,
    userContext: nil)

  adsLoader.requestAds(with: request)
}

Objective-C


- (void)setupAdsLoader {
  self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:nil];
  self.adsLoader.delegate = self;
}

测试

如果您希望在应用开发过程中测试集成,请按照以下步骤以编程方式注册您的测试设备。在发布应用之前,请务必移除用于设置这些测试设备 ID 的代码。

  1. 欢迎致电 requestConsentInfoUpdateWithParameters:completionHandler:
  2. 检查日志输出,以查找类似于以下示例的消息(向您显示您的设备 ID 以及如何将设备添加为测试设备):

    <UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. 将测试设备 ID 复制到剪贴板。

  4. 修改代码,以便调用 UMPDebugSettings().testDeviceIdentifiers 并将其传入您的测试设备 ID 列表。

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

强制调试地理位置

UMP SDK 提供了一种方法:使用 UMPDebugGeography 测试您的应用行为,就像设备位于欧洲经济区 (EEA) 或英国境内一样。请注意,调试设置仅适用于测试设备。

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

通过 UMP SDK 测试应用时,您可能会发现重置 SDK 的状态很实用,因为您可以模拟用户的首次安装体验。该 SDK 提供的 reset 方法可实现此目的。

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

GitHub 上的示例

如需查看本页介绍的 UMP SDK 集成的完整示例,请参阅 Swift UmpExample Objective-C UmpExample