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 đưa ra một số thông tin công bố 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, đồng thời có được sự đồng ý của họ để sử dụng cookie hoặc các phương pháp lưu trữ 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ư mã nhận dạng cho quảng cáo (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 cũng như Quy định chung về việc bảo vệ dữ liệu (GDPR).

Để giúp các nhà xuất bản đáp ứng 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). UMP SDK đã đượ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ể xử lý tất cả các cấu hình này một cách thuận tiện 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 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 tài khoản AdMob . SDK UMP cố gắng hiển thị một thông báo cho người dùng được tạo từ AdMob Mã ứng dụng được đặt 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, 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)

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 và thêm dòng này vào mục tiêu của ứng dụng:

pod 'GoogleUserMessagingPlatform'

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 Podfile.

Trình quản lý gói Swift

SDK UMP cũng hỗ trợ Trình quản lý gói Swift. Hãy làm theo các bước sau để nhập gói Swift.

  1. Trong Xcode, hãy cài đặt Gói Swift SDK UMP bằng cách chuyển đến File > Add Packages... (Tệp > Thêm gói).

  2. Khi lời nhắc xuất hiện, hãy tìm kho lưu trữ UMP SDK Swift Package GitHub:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Chọn phiên bản của Gói Swift SDK UMP mà bạn muốn sử dụng. Đối với các dự án mới, bạn nên sử dụng tính năng Up to Next Major Version (Lên đến phiên bản lớn tiếp theo).

Sau đó, Xcode sẽ giải quyết các phần phụ thuộc của gói và tải các phần đó xuống ở chế độ nền. Để biết thêm thông tin về cách thêm các phần phụ thuộc của gói, hãy xem bài viết của Apple.

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ề sự đồng ý của người dùng mỗi khi khởi 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ó cần đưa ra sự đồng ý hay không (nếu họ chưa làm vậy) hay 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()

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

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

Quan trọng: Các API sau đây tương thích với SDK Nền tảng thông báo cho người dùng (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 đồng ý. Nếu trạng thái đồng ý là bắt buộc, SDK sẽ tải một biểu mẫu và ngay lập tức hiển thị biểu mẫu đó từ view controllerđược cung cấp. completion handler sẽ được gọi sau khi biểu mẫu bị loại bỏ. Nếu không cần có sự đồng ý, thì completion handler sẽ được gọi ngay lập tức.

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

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 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ó 2 nơi để kiểm tra trong quá trình thu thập sự đồng ý:

  1. Sau khi có được sự đồng ý trong phiên hiện tại.
  2. Ngay sau khi bạn gọi 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 ngay khi có thể 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 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()

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

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

Một số biểu mẫu đồ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 đây để 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 trong trang cài đặt của ứng dụng, để có thể kích hoạt biểu mẫu các tuỳ chọn về quyền riêng tư.
  2. Sau khi loadAndPresentIfRequiredFromViewController:completionHandler: hoàn tất, hãy kiểm traprivacyOptionsRequirementStatus để 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 phần tử trên giao diện người dùng, hãy gọipresentPrivacyOptionsFormFromViewController:completionHandler: để hiển thị biểu mẫu và người dùng có thể cập nhật các tuỳ chọn quyền riêng tư của họ bất cứ lúc nào.

Ví dụ sau cho thấy cách trình bày biểu mẫu các tuỳ chọn quyền riêng tư từ 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.
                                  }
                                }];
}

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 sau để đăng ký thiết bị kiểm thử theo phương thức lập trình. Hãy nhớ xóa mã dùng để đặt các mã thiết bị thử nghiệm này trước khi bạn phát hành ứng dụng.

  1. Gọi requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Kiểm tra đầu ra nhật ký để tìm một thông báo tương tự như ví dụ sau. Thông báo này cho biết mã thiết bị của bạn và cách thêm mã thiết bị đó 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ã để gọi UMPDebugSettings().testDeviceIdentifiers và chuyể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 ở 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ế độ gỡ lỗi chỉ hoạt động trên thiết bị thử nghiệm.

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 kiểm thử ứng dụng bằng UMP SDK, 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 để thực hiện 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 (UMP): Swift | Objective-C