Bắt đầu

Theo Chính sách về sự đồng ý của người dùng ở Liên minh Châu Âu của Google, bạn phải công bố một số thông tin nhất định cho người dùng ở Khu vực kinh tế Châu Âu (EEA) cùng với Vương quốc Anh và có được sự đồng ý của họ về việc sử dụng cookie hoặc bộ nhớ cục bộ khác khi pháp luật yêu cầu và để sử dụng dữ liệu cá nhân (chẳng hạn như AdID) để phân phát quảng cáo. Chính sách này thể hiện các yêu cầu của Chỉ thị về quyền riêng tư và truyền thông điện tử của Liên minh Châu Âu và Quy định chung về việc bảo vệ dữ liệu (GDPR).

Để giúp các nhà xuất bản thực hiện các nghĩa vụ của họ theo chính sách này, Google cung cấp SDK Nền tảng thông báo cho người dùng (UMP). SDK UMP đã được cập nhật để hỗ trợ các tiêu chuẩn mới nhất của IAB. Giờ đây, bạn có thể dễ dàng xử lý tất cả các cấu hình này trong phần AdMob quyền riêng tư và thông báo.

Điều kiện tiên quyết

Tạo một loại thông báo

Tạo thông báo cho người dùng bằng một trong các loại thông báo hiện có cho người dùng trong thẻ Quyền riêng tư và thông báo của AdMob tài khoản. SDK UMP sẽ cố gắng hiển thị một thông báo cho người dùng được tạo từ tập hợp AdMob Mã ứng dụng trong dự án của bạn. Nếu không có thông báo nào được định cấu hình cho ứng dụng của bạn, thì SDK sẽ trả về lỗi.

Để biết thêm thông tin, hãy xem bài viết Giới thiệu về quyền riêng tư và thông báo.

Nhập SDK

CocoaPods (ưu tiên)

SDK UMP nằm trong phần phụ thuộc của nhóm SDK quảng cáo trên thiết bị di động của Google kể từ SDK quảng cáo trên thiết bị di động của Google phiên bản 7.64.0.

Cách dễ nhất để nhập SDK vào một dự án iOS là sử dụng CocoaPods. Hãy mở Podfile của dự án, rồi thêm dòng này vào mục tiêu của ứng dụng:

pod 'Google-Mobile-Ads-SDK'

Sau đó, hãy chạy lệnh sau:

pod install --repo-update

Nếu bạn mới sử dụng CocoaPods, hãy xem bài viết Sử dụng CocoaPods để biết thông tin chi tiết về cách tạo và sử dụng Podfiles.

Tự tải xuống

Một cách khác để nhập SDK là nhập theo cách thủ công.

Tải SDK xuống

Sau đó, hãy kéo khung này vào dự án Xcode của bạn và nhớ chọn Sao chép các mục nếu cần.

Sau đó, bạn có thể thêm khung này vào bất kỳ tệp nào bạn cần bằng cách sử dụng:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Bạn nên yêu cầu cập nhật thông tin về trạng thái đồng ý của người dùng mỗi lần chạy ứng dụng, bằng cách sử dụng requestConsentInfoUpdateWithParameters:completionHandler:. Điều này xác định liệu người dùng của bạn có cần phải đưa ra sự đồng ý hay không nếu họ chưa làm vậy, hoặc nếu trạng thái đồng ý của họ đã hết hạn.

Dưới đây là ví dụ về cách kiểm tra trạng thái từ UIViewController trong phương thức viewDidLoad().

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Create a UMPRequestParameters object.
  let parameters = UMPRequestParameters()
  // Set tag for under age of consent. false means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = false

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

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }

            // TODO: Load and present the consent form.
          }];
}

Tải và trình bày biểu mẫu lấy sự đồng ý (nếu bắt buộc)

Lưu ý quan trọng: Các API sau đây tương thích với SDK UMP phiên bản 2.1.0 trở lên.

Sau khi bạn nhận được trạng thái đồng ý mới nhất, hãy gọi loadAndPresentIfRequiredFromViewController:completionHandler: trên lớp UMPConsentForm để tải biểu mẫu lấy sự đồng ý. Nếu phải có trạng thái đồng ý, SDK sẽ tải một biểu mẫu và hiển thị biểu mẫu đó ngay từ view controllerđược cung cấp. completion handler được gọi sau khi biểu mẫu bị đóng. Nếu không cần có sự đồng ý, thì completion handler để gọi ngay lập tức.

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Create a UMPRequestParameters object.
  let parameters = UMPRequestParameters()
  // Set tag for under age of consent. false means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = false

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

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          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.
                }];
          }];
}

Nếu bạn cần thực hiện bất kỳ hành động nào sau khi người dùng đã đưa ra sự lựa chọn hoặc đóng biểu mẫu, hãy đặt logic đó vào completion handlercho biểu mẫu của bạn.

Yêu cầu quảng cáo

Trước khi yêu cầu quảng cáo trong ứng dụng của bạn, hãy kiểm tra xem bạn có được người dùng đồng ý bằng cách sử dụng UMPConsentInformation.sharedInstance.canRequestAdshay không. Có hai vị trí để kiểm tra trong khi thu thập sự đồng ý:

  1. Sau khi thu thập được sự đồng ý trong phiên hiện tại.
  2. Ngay sau khi bạn gọi điện cho requestConsentInfoUpdateWithParameters:completionHandler:. Có thể bạn đã nhận được sự đồng ý trong phiên trước. Một phương pháp hay nhất về độ trễ là bạn không nên đợi lệnh gọi lại hoàn tất để có thể bắt đầu tải quảng cáo càng sớm càng tốt sau khi ứng dụng khởi chạy.

Nếu xảy ra lỗi trong quá trình thu thập sự đồng ý, bạn vẫn nên tìm cách yêu cầu quảng cáo. SDK UMP sử dụng trạng thái đồng ý từ phiên hoạt động trước đó.

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()

    // Create a UMPRequestParameters object.
    let parameters = UMPRequestParameters()
    // Set tag for under age of consent. false means users are not under age
    // of consent.
    parameters.tagForUnderAgeOfConsent = false

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

  // Create a UMPRequestParameters object.
  UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
  // Set tag for under age of consent. NO means users are not under age
  // of consent.
  parameters.tagForUnderAgeOfConsent = NO;

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          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...];
  });
}

Tuỳ chọn về quyền riêng tư

Một số biểu mẫu lấy sự đồng ý yêu cầu người dùng sửa đổi sự đồng ý của họ bất cứ lúc nào. Hãy làm theo các bước sau để triển khai nút tuỳ chọn quyền riêng tư nếu cần.

Để thực hiện điều này:

  1. Triển khai một thành phần trên giao diện người dùng (chẳng hạn như một nút) trên trang cài đặt của ứng dụng để kích hoạt biểu mẫu tuỳ chọn về quyền riêng tư.
  2. Sau khi loadAndPresentIfRequiredFromViewController:completionHandler: hoàn tất, hãy kiểm tra privacyOptionsRequirementStatus để xác định xem có hiển thị thành phần trên giao diện người dùng có thể hiển thị biểu mẫu tuỳ chọn quyền riêng tư hay không.
  3. Khi người dùng tương tác với thành phần trên giao diện người dùng, hãy gọipresentPrivacyOptionsFormFromViewController:completionHandler: để hiển thị biểu mẫu nhằm người dùng có thể cập nhật các tuỳ chọn về quyền riêng tư của họ bất cứ lúc nào.

Ví dụ sau đây cho biết cách trình bày biểu mẫu tuỳ chọn quyền riêng tư từ UIBarButtonItem.

Swift

@IBOutlet weak var privacySettingsButton: UIBarButtonItem!

var isPrivacyOptionsRequired: Bool {
  return UMPConsentInformation.shared.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.
                                  }
                                }];
}

Kiểm thử

Nếu bạn muốn kiểm thử tính năng tích hợp trong ứng dụng khi đang phát triển, hãy làm theo các bước dưới đây để đăng ký thiết bị kiểm thử theo phương thức lập trình.

  1. Gọi requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Kiểm tra đầu ra nhật ký để tìm một thông báo có dạng như bên dưới. Thông báo này cho bạn biết mã thiết bị của bạn và cách thêm thông báo đó làm thiết bị thử nghiệm:

    <UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. Sao chép mã thiết bị thử nghiệm vào bảng nhớ tạm.

  4. Sửa đổi mã của bạn để gọi UMPDebugSettings().testDeviceIdentifiers và truyền vào danh sách mã thiết bị thử nghiệm.

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

Chỉ định một vị trí địa lý

SDK UMP cung cấp một cách để kiểm thử hành vi của ứng dụng như thể thiết bị được đặt tại Khu vực kinh tế Châu Âu (EEA) hoặc Vương quốc Anh bằng cách sử dụng the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Xin lưu ý rằng chế độ cài đặt gỡ lỗi chỉ hoạt động trên thiết bị kiểm thử.

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

Khi thử nghiệm ứng dụng bằng SDK UMP, bạn nên đặt lại trạng thái của SDK để có thể mô phỏng trải nghiệm cài đặt lần đầu của người dùng. SDK sẽ cung cấp phương thức reset để làm việc này.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

Ví dụ trên GitHub

Ví dụ về cách tích hợp SDK Nền tảng thông báo cho người dùng: Swift | Objective-C