開始使用

根據 Google《歐盟地區使用者同意授權政策》規定,您必須向歐洲經濟區 (EEA) 和英國境內的使用者揭露特定資訊,且必須依法取得使用者同意,才能使用 Cookie 或其他本機儲存空間,以及使用個人資料 (例如廣告 ID) 放送廣告。本政策是配合《歐盟地區電子通訊隱私指令》和《一般資料保護規則》(GDPR) 而製定。

為了協助發布商根據這項政策履行自身職責,Google 提供了 User Messaging Platform (UMP) SDK。UMP SDK 已更新,現已支援最新的 IAB 標準。這些設定現在全都可在隱私權與訊息中 Ad Manager 輕鬆處理。

先備知識

建立訊息類型

使用其中一種 可用的使用者訊息類型 在 AdMob 帳戶的「隱私權與訊息」分頁中建立 Ad Manager 帳戶。UMP SDK 會嘗試顯示從專案中設定的 Ad Manager 應用程式 ID 建立的使用者訊息。如果未設定應用程式訊息,SDK 會傳回錯誤。

詳情請參閱 隱私權與訊息簡介

匯入 SDK

CocoaPods (建議)

要將 SDK 匯入 iOS 專案,最簡單的方法是使用 CocoaPods。開啟專案的 Podfile,並將這一行新增至應用程式目標:

pod 'GoogleUserMessagingPlatform'

接著執行下列指令:

pod install --repo-update

如果您是 CocoaPods 新手,請參閱「使用 CocoaPods」一文,進一步瞭解如何建立及使用 Podfiles。

Swift 套件管理工具

UMP SDK 也支援 Swift 套件管理工具。請按照下列步驟匯入 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 套件版本。如要建立新專案,建議您使用直到下一個主要版本

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

手動下載

匯入 SDK 的另一種方式則是手動進行。

下載 SDK

然後將架構拖曳至 Xcode 專案,確認已選取「Copy itemss if needed」

然後,您可以使用下列任何所需檔案加入架構:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

您應在每次應用程式啟動時,使用 requestConsentInfoUpdateWithParameters:completionHandler:要求更新使用者的同意聲明資訊。這會決定使用者是否必須在尚未同意或同意聲明已過期的情況下提供同意聲明。

以下範例說明如何透過 viewDidLoad() 方法,從 UIViewController 檢查狀態。

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

視需要載入並顯示同意聲明表單

收到最新的同意聲明狀態後,請對UMPConsentForm 類別呼叫loadAndPresentIfRequiredFromViewController:completionHandler: 以載入同意聲明表單。如果需要同意聲明狀態,SDK 會載入表單,並立即透過 提供的 view controller顯示表單。關閉表單後,系統會 completion handler 此作業 。如果不需要徵求同意,系統會立即 completion handler 。

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

如果您需要在使用者做出選擇或關閉表單後執行任何動作,請將該邏輯放入表單的 completion handler中。

請求廣告

在應用程式中請求廣告前,請確認您已使用 UMPConsentInformation.sharedInstance.canRequestAds取得使用者的同意聲明。收集同意聲明時,需要檢查兩個地方:

  1. 從目前的工作階段中收集到同意聲明後,
  2. 呼叫 requestConsentInfoUpdateWithParameters:completionHandler:後立即執行。您可能已在上一個工作階段取得同意聲明。建議您最好不要等待回呼完成,以便在應用程式啟動後盡快載入廣告。

如果在收集同意聲明的過程中發生錯誤,您還是可以嘗試請求廣告。UMP SDK 會使用上一個工作階段的同意聲明狀態。

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

隱私權選項

部分同意聲明表單會要求使用者隨時修改同意聲明。如有需要,請按照下列步驟導入隱私權選項按鈕。

為了達到這個目的:

  1. 實作可觸發隱私權選項表單的 UI 元素,例如應用程式設定頁面中的按鈕。
  2. 完成 loadAndPresentIfRequiredFromViewController:completionHandler: 完成後,請檢查privacyOptionsRequirementStatus 判斷是否要顯示能顯示隱私權選項表單的 UI 元素。
  3. 當使用者與您的 UI 元素互動時,請呼叫presentPrivacyOptionsFormFromViewController:completionHandler: 來顯示表單,方便使用者隨時更新隱私權選項。

以下範例說明如何顯示來自 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.
                                  }
                                }];
}

測試

如要在開發過程中測試應用程式的整合作業,請按照下列步驟,以程式輔助方式註冊測試裝置。發布應用程式之前,請務必移除用來設定這些測試裝置 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 可讓您使用 the debugGeography property of type UMPDebugGeography on UMPDebugSettings測試應用程式行為,就像裝置在歐洲經濟區或英國一樣。請注意,偵錯設定僅適用於測試裝置。

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 | Objective-C