開始使用

Google User Messaging Platform (UMP) SDK 是隱私權和訊息工具,可協助您管理隱私權選項。詳情請參閱「關於隱私權與訊息」。您可以在 Objective-CSwift UMP 範例應用程式中,查看使用 UMP SDK 的 IMA 實作功能。

建立訊息類型

在 Ad Manager 帳戶的「隱私權與訊息」分頁中,使用任一可用的使用者訊息類型建立使用者訊息。UMP SDK 會嘗試顯示根據您專案中設定的互動式媒體廣告應用程式 ID 建立的隱私權訊息。

詳情請參閱隱私權和訊息功能簡介

匯入 SDK

UMP SDK 並非 IMA 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 Package。

  2. 在隨即顯示的提示中,搜尋 UMP SDK Swift Package GitHub 存放區:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. 選取要使用的 UMP SDK Swift 套件版本。對於新專案,建議您使用升級至下一個主要版本

接著,Xcode 會解析套件依附元件,並在背景下載這些依附元件。如要進一步瞭解如何新增套件依附元件,請參閱 Apple 的文章

新增應用程式 ID

您可以在 Ad Manager UI 中找到應用程式 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;
}

在應用程式中新增可見元素

如果需要隱私權進入點,請在應用程式中新增可見且可互動的 UI 元素,以便顯示隱私權選項表單。如果不需要隱私權進入點,請將 UI 元素設為不可見且無法互動。

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 測試應用程式的行為,就像該裝置位於歐洲經濟區或英國境內一樣。請注意,偵錯設定只適用於測試裝置。

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