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, đồng thời có được sự đồng ý của họ để 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ư mã nhận dạng cho quảng cáo) để 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).

Để hỗ trợ 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 IAB mới nhất. 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 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 cho người dùng hiện có 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ị 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 bạn chưa định cấu hình thông báo nào cho ứng dụng, thì SDK sẽ trả về một 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 đó, chạy lệnh sau:

pod install --repo-update

Nếu bạn mới sử dụng CocoaPods, hãy xem phần 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. Làm theo các bước sau để nhập gói Swift.

  1. Trong Xcode, hãy cài đặt Gói UMP SDK Swift 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ữ GitHub UMP SDK Swift Package:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Chọn phiên bản 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 phiên bản Up to Next Major Version (Lên phiên bản lớn tiếp theo).

Sau đó, Xcode sẽ phân giải 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 chi tiết 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ải xuống theo cách thủ cô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ể đưa 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 lần khởi chạy ứng dụng, bằng cách sử dụng requestConsentInfoUpdateWithParameters:completionHandler:. Điều này sẽ xác định liệu người dùng cần đưa ra sự đồng ý nếu họ chưa làm vậy hay khi sự đồ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 một biểu mẫu lấy sự đồng ý (nếu cầ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 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à hiển thị ngay lập tức từ view controllerđược cung cấp. completion handler được gọi sau khi biểu mẫu bị loại bỏ. Nếu người dùng không cần phải 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, hãy kiểm tra xem bạn đã nhận được sự đồng ý của người dùng đang sử dụng UMPConsentInformation.sharedInstance.canRequestAdshay chưa. Có 2 vị trí cần kiểm tra trong quá trình 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 requestConsentInfoUpdateWithParameters:completionHandler:. Có thể bạn đã nhận được sự đồng ý trong buổi chia sẻ trước. Tốt nhất 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 ý, thì 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 ý của 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()

    // 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ư nút trên trang cài đặt của ứng dụng, để có thể kích hoạt biểu mẫu về các lựa 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 các tuỳ chọn về 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 giúp 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 đây cho thấy cách trình bày biểu mẫu các lựa chọn về 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ử việc 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ớ xoá 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ư sau. Ví dụ này cho biết mã thiết bị của bạn và cách thêm thông báo đó làm thiết bị kiểm thử:

    <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ọiUMPDebugSettings().testDeviceIdentifiers và chuyển vào danh sách mã thiết bị thử nghiệm của bạn.

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

Buộc hiển thị một khu vực đị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ị nằm ở Khu vực kinh tế Châu Âu (EEA) hoặc Vương quốc Anh thông qua the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Xin lưu ý rằng các chế độ cài đặt 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 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 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ề việc tích hợp SDK Nền tảng thông báo cho người dùng (UMP SDK): Swift | Objective-C