Di chuyển SDK

Trang này trình bày cách di chuyển đối với phiên bản hiện tại và phiên bản trước đây của Google SDK quảng cáo trên thiết bị di động dành cho iOS. Phiên bản 11.0.0 dự kiến sẽ ra mắt vào tháng 1 2024.

Chuyển từ SDK phiên bản 10 sang phiên bản 11

部署目标下限

最低部署目标已提高至 iOS 12。

最低 Xcode 版本

支持的最低 Xcode 版本已提高至 15.1。

广告停止在 iOS 12 设备上投放

Google 移动广告 SDK 版本 11.0.0 仅在搭载 iOS 13 及更高版本的设备上投放广告。

移除了 GoogleAppMeasurement 依赖项

在版本 11.0.0 中,移除了对 GoogleAppMeasurement 的依赖。这个为 AdMob 中用户指标切换开关提供支持的依赖项将于 2024 年初停用。如需继续在 AdMob 中收集用户指标,请将您的 AdMob 应用关联到 Firebase,并将 Google Analytics for Firebase SDK 集成到您的应用中。

全屏广告展示方式的变化

以下变更会影响各种广告格式:

  • 开屏广告
  • 插页式广告
  • 已奖励
  • 插页式激励广告

-canPresentFromRootViewController:error:-presentFromRootViewController: 中的视图控制器参数可为 null。如果传递 nil,则广告会从视图控制器层次结构中的最顶层视图控制器展示。

移除的方法

系统会移除以下方法。

v11.0.0 类型 方法 备注
GADAppOpenAd load(withAdUnitID adUnitID: String, request: GADRequest?, orientation: UIInterfaceOrientation) 请改用 load(withAdUnitID adUnitID: String, request: GADRequest?)
GADMediationBannerAdEventDelegate willBackgroundApplication() 无替代项。
GADMediationInterstitialAdEventDelegate willBackgroundApplication() 无替代项。
GADMediationNativeAdEventDelegate willBackgroundApplication() 无替代项。
GADMediationRewardedAdEventDelegate didRewardUser(with reward: GADAdReward) 请改用 didRewardUser()
GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillLeaveApplication(_ mediatedNativeAd: GADMediatedUnifiedNativeAd) 无替代项。
GADRequestConfiguration setSameAppKeyEnabled(_ enabled: Bool) 请改用 setPublisherFirstPartyIDEnabled(_ enabled: Bool)
tagForUnderAge(ofConsent underAgeOfConsent: Bool) 请改用 tagForUnderAgeOfConsent 属性。
tag(forChildDirectedTreatment childDirectedTreatment: Bool) 请改用 tagForChildDirectedTreatment 属性。

已移除的属性

已移除以下属性。

v11.0.0 中的类 媒体资源 备注
GADMediationAdConfiguration hasUserLocation 无替代项。
userLatitude
userLongitude
userLocationAccuracyInMeters
childDirectedTreatment 请改用 GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment
GADResponseInfo adNetworkClassName 请改用 loadedAdNetworkResponseInfo 中的 adNetworkClassName

移除了 GADAdFormatUnknown

移除了 GADAdFormatUnknown,且无替代项。

日志记录 SDK 版本的更改

11.0.0 版移除了 sdkVersion。如需记录 Google 移动广告 SDK 版本,请改用 versionNumber

版本 10.0.0

GADMobileAds.sharedInstance().sdkVersion

版本 11.0.0

GADGetStringFromVersionNumber(GADMobileAds.sharedInstance().versionNumber)

对 GADAdLoader 错误处理方式的更改

从 11.0.0 版开始,如果 GADAdLoaderdelegate 不符合所请求广告类型的委托协议,则不会发出广告请求。之前,该调用在发出广告请求后就会失败。

测试行为变更

请参阅表格,了解以下属性何时返回 true 的更新条件。

媒体资源
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • testDeviceIdentifiers 中将设备明确声明为测试设备。
  • testDeviceIdentifiers 中将设备明确声明为测试设备。
  • 设备是一个模拟器。
  • 在 AdMob 界面中将设备明确声明为测试设备。

Chuyển từ phiên bản 9 sang phiên bản 10

Ngừng phân phát quảng cáo trên iOS 11

SDK quảng cáo trên thiết bị di động của Google phiên bản 10.0.0 chỉ phân phát quảng cáo trên các thiết bị chạy iOS 12 trở lên.

Việc nâng cấp lên SDK quảng cáo trên thiết bị di động của Google phiên bản 10.0.0 sẽ không khiến ứng dụng của bạn gặp lỗi trên các thiết bị iOS 11 và iOS 10. Tuy nhiên, quảng cáo sẽ không được phân phát trên các thiết bị đó.

Việc xây dựng chương trình bằng mã bit không còn được hỗ trợ nữa

Hiện tại, bạn phải tắt mã bit trong ứng dụng di động để tích hợp SDK quảng cáo trên thiết bị di động của Google.

Các loại đã bị xoá

Loại Ghi chú
GADGender Không có loại thay thế.
GADMRewardBasedVideoAdNetworkAdapterProtocol Tất cả các bộ chuyển đổi dàn xếp có tặng thưởng được nêu trong mục Chọn mạng đã ngừng sử dụng các giao thức này trong hơn một năm qua. Hãy sử dụng GADMediationAdapter cho hoạt động dàn xếp và các sự kiện tuỳ chỉnh.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Các thuộc tính đã bị xoá

Các thuộc tính sau đã bị xoá mà không có thuộc tính thay thế.

Lớp phiên bản 10.0.0 Tài sản
GADMediationAdRequest userBirthday
userGender
userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
userLatitude
userLongitude
userLocationAccuracyInMeters
userLocationDescription

Chuyển từ phiên bản 8 sang phiên bản 9

广告停止在 iOS 10 设备上投放

Google 移动广告 SDK 版本 9.0.0 支持的最低 iOS 版本是 iOS 11。

升级到 Google 移动广告 SDK 版本 9.0.0 不会影响您的应用在 iOS 10 设备上的行为,但广告不会在这些设备上投放。

状态栏控制规定的执行更严格

从版本 9.0.0 开始,当您展示全屏格式的广告时,您的应用应确保广告能够控制状态栏的显示。如果您未能这样做,将会在日志中看到一条错误消息。

根据应用中视图控制器的具体布局,您可能无需做出任何更改即可确保实现这一点。考虑您是否需要在广告的 rootViewController 上设置 childViewControllerForStatusBarHidden 属性。

将 adDidPresentFullScreenContent: 重命名为 adWillPresentFullScreenContent:

行为无变化。委托方法在广告即将展示之前调用,因此新的方法名称可以更好地体现其功能。

移除了 GADRequest 上的 Location Settings API

- (void)setLocationWithLatitude:longitude:accuracy: 已从 GADRequest 中删除,因为 Google 不使用位置数据来定位广告。如果需要,请使用第三方 API 向第三方广告联盟提供该信息。

弃用了自定义事件接口

借助自定义事件,使用 AdMob 中介的发布商可以为支持的广告联盟以外的广告联盟添加广告瀑布流中介。

所有自定义事件协议均已弃用。请改用现有的 GADMediationAdapterGADMediationAdEventDelegate 协议来实现相同的功能。这项变更让表达更加清晰明确,还可让您为之前不可用的激励广告和插页式滚显广告创建自定义事件。

API

下表列出了从版本 9.0.0 开始应使用的 Custom Events API 所对应的 Mediation Adapter API。

v8 v9
GADCustomEventBanner
GADCustomEventInterstitial
GADCustomEventNativeAd
GADMediationAdapter GADMediationBannerAd
GADMediationInterstitialAd
GADMediationInterscrollerAd
GADMediationRewardedAd
GADMediationNativeAd
delegate 委托由 GADMediationAdapter 类的每个加载函数的加载完成处理程序返回
-init -init
-requestBannerAd:parameter:label:request: -loadBannerForAdConfiguration:completionHandler:
-requestInterstitialAdWithParameter:label:request: -loadInterstitialForAdConfiguration:completionHandler:
-requestNativeAdWithParameter:request:adTypes:options:rootViewController: -loadNativeAdForAdConfiguration:completionHandler:
不适用 -loadInterscrollerAdForAdConfiguration:completionHandler:
不适用 -loadRewardedAdForAdConfiguration:completionHandler:
-presentFromRootViewController: -presentFromViewController:
-handlesUserClicks -handlesUserClicks
-handlesUserImpressions -handlesUserImpressions

委托方法

下表列出了从版本 9.0.0 开始应使用的自定义事件委托方法所对应的中介广告事件委托方法。

v8 v9
GADCustomEventBannerDelegate
GADCustomEventInterstitialDelegate
GADCustomEventNativeAdDelegate
GADMediationAdEventDelegate GADMediationAd
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
广告加载状态包含在 GADMediationAdapter 类中每个加载函数的加载完成处理程序中
-customEventBanner:didFailAd:
-customEventInterstitial:didFailAd:
-customEventBannerWasClicked:
-customEventInterstitialWasClicked:
-reportClick
-customEventBannerWillPresentModal:
-customEventInterstitialWillPresentModal:
-willPresentFullScreenView
-customEventBannerWillDismissModal:
-customEventInterstitialWillDismissModal:
-willDismissFullScreenView
-customEventBannerDidDismissModal:
-customEventInterstitialDidDismissModal:
-didDismissFullScreenView
-customEventBannerWillLeaveApplication:
-customEventInterstitialWillLeaveApplication:
-willBackgroundApplication
viewControllerForPresentingModalView -[GADMediationBannerAd view]

其他已移除/替换的方法和常量

对方法、常量或属性的变更
kGAD- 前缀的常量 已移除。使用带 GAD- 前缀的常量。
GADAdNetworkResponseInfo 移除了 credentials。请改用 adUnitMapping
GAMRequest 废弃了 GAMRequest 中的 kGAMSimulatorID。请在 GADRequestConfiguration 中改用 GADSimulatorID
GADCustomNativeAd 废弃了 GADCustomNativeAd 中的 mediaView。请改用 mediaContent
GoogleMobileAds 中的 In-App Purchase API 移除了 GoogleMobileAds 中的 inAppPurchase API。

Chuyển từ phiên bản 7 sang phiên bản 8

SDK quảng cáo trên thiết bị di động của Google phiên bản 8.0.0 có một số thay đổi chính, đồng thời, một số API sẽ được đổi tên và một số API bị xoá.

Nội dung cập nhật đối với API theo định dạng toàn màn hình

Kể từ phiên bản 8.0.0, quảng cáo xen kẽ và quảng cáo có tặng thưởng sẽ dùng chung một kiểu quảng cáo toàn màn hình chung để tăng tính nhất quán. Các API quảng cáo toàn màn hình mới này có hai điểm khác biệt chính so với các API quảng cáo toàn màn hình phiên bản 7:

  1. Phương thức lớp tĩnh load.

    Trước đây, để tải/hiển thị quảng cáo toàn màn hình như sau:

    1. Tạo một thực thể đối tượng quảng cáo và giữ tệp tham chiếu đến đối tượng đó.
    2. Chỉ định một thực thể đại diện xử lý các lệnh gọi lại tải và hiển thị.
    3. Tải một quảng cáo.
    4. Kiểm tra xem quảng cáo có được tải bằng isReady hay không.
    5. Hiển thị quảng cáo.

    Trong phiên bản 8, cách tiếp cận có thay đổi đôi chút. Các lệnh gọi lại tải không còn là một phần của thực thể đại diện nữa. Thay vào đó, các sự kiện này được chuyển vào phương thức load dưới dạng trình xử lý hoàn thành:

    1. Gọi một phương thức tải tĩnh trên lớp quảng cáo và cung cấp một trình xử lý tải hoàn thành.
    2. Trong lệnh gọi lại tải hoàn thành, hãy giữ lại tệp tham chiếu đến quảng cáo đã tải sẽ được trả về.
    3. Chỉ định một thực thể đại diện xử lý các lệnh gọi lại hiển thị.
    4. Hiển thị quảng cáo.

    Cách tiếp cận mới mang lại những lợi ích sau:

    • Bạn sẽ không bao giờ có tệp tham chiếu đến quảng cáo chưa được tải.
    • Bạn không phải giữ một đối tượng quảng cáo trong khi đang tải.
  2. Sự kiện quảng cáo đều đặn.

    Loại sự kiện API hiện có API phiên bản 8
    Sự kiện tải GADInterstitialDelegate hoặc GADRewardedAdDelegate GADInterstitialAdLoadCompletionHandler hoặc GADRewardedAdLoadCompletionHandler
    Sự kiện trình bày GADFullScreenContentDelegate

    Trước đây, để theo dõi bất kỳ sự kiện quảng cáo nào, bạn cần đăng ký một lớp sẽ triển khai giao thức GADInterstitialDelegate cho thuộc tính uỷ quyền của quảng cáo xen kẽ hoặc đăng ký một lớp triển khai giao thức GADRewardedAdDelegate cho thuộc tính uỷ quyền của quảng cáo có tặng thưởng tuỳ thuộc vào định dạng bạn đang sử dụng. Thực thể đại diện này có các phương thức liên quan đến cả vòng đời tải và trình bày của một quảng cáo.

    Với phiên bản 8, các sự kiện tải và trình bày là riêng biệt. Giờ đây, bạn có thể đăng ký GADFullScreenContentDelegate bất cứ lúc nào trước khi hiển thị quảng cáo thay vì phải đặt một thực thể đại diện trước khi tải quảng cáo. Các sự kiện tải quảng cáo (cụ thể cho từng định dạng) sẽ chuyển sang một trình xử lý tải hoàn thành được chuyển vào phương thức tải.

Quảng cáo xen kẽ

Tải quảng cáo

Các đoạn mã dưới đây cho bạn biết cách tải quảng cáo xen kẽ và theo dõi các sự kiện khi quảng cáo tải thành công hoặc không tải được.

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADInterstitialDelegate {

  var interstitial: GADInterstitial!

  override func viewDidLoad() {
    super.viewDidLoad()
    interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
    interstitial.delegate = self
    let request = GADRequest()
    interstitial.load(request)
  }

  /// Tells the delegate an ad request succeeded.
  func interstitialDidReceiveAd(_ ad: GADInterstitial) {
    print("Interstitial ad loaded.")
  }

  /// Tells the delegate an ad request failed.
  func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
    print("Interstitial ad failed to load with error: \(error.localizedDescription)")
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADInterstitial *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[GADInterstitial alloc]
      initWithAdUnitID:@"ca-app-pub-3940256099942544/4411468910"];
  self.interstitial.delegate = self;
  GADRequest *request = [GADRequest request];
  [self.interstitial loadRequest:request];
}

/// Tells the delegate an ad request succeeded.
- (void)interstitialDidReceiveAd:(GADInterstitial *)ad {
  NSLog(@"Insterstitial ad loaded.");
}

/// Tells the delegate an ad request failed.
- (void)interstitial:(GADInterstitial *)ad
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"Interstitial ad failed to load with error: %@", [error localizedDescription]);
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  var interstitial: GADInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    let request = GADRequest()
    GADInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                                request: request,
                      completionHandler: { (ad, error) in
                        if let error = error {
                          print("Failed to load interstitial ad with error: \(error.localizedDescription)")
                          return
                        }
                        self.interstitial = ad
                        self.interstitial.fullScreenContentDelegate = self
                      }
    )
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADInterstitialAd *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  GADRequest *request = [GADRequest request];
  [GADInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/4411468910"
                              request:request
                    completionHandler:^(GADInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

Quảng cáo hiển thị

v7

Swift

func showInterstitial() {
  ...
  if interstitial.isReady {
    interstitial.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial.isReady) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

v8

Swift

func showInterstitial() {
  ...
  if let ad = interstitial {
    ad.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

Sự kiện quảng cáo trình bày

Các đoạn mã dưới đây cho bạn biết cách xử lý các lệnh gọi lại khi quảng cáo hiển thị (thành công hoặc không thành công) và khi quảng cáo bị loại bỏ.

v7

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
  interstitial.delegate = self
  ...
}

/// Tells the delegate that an interstitial will be presented.
func interstitialWillPresentScreen(_ ad: GADInterstitial) {
  print("Interstitial ad will be presented.")
}

/// Tells the delegate the interstitial is to be animated off the screen.
func interstitialWillDismissScreen(_ ad: GADInterstitial) {
  print("Interstitial ad will be dismissed.")
}

/// Tells the delegate the interstitial had been animated off the screen.
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
  print("Interstitial ad dismissed.")
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
func interstitialWillLeaveApplication(_ ad: GADInterstitial) {
  print("Interstitial ad will leave application.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:"ca-app-pub-3940256099942544/4411468910"];
  self.interstitial.delegate = self;
  ...
}

/// Tells the delegate that an interstitial will be presented.
- (void)interstitialWillPresentScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will be presented.");
}

/// Tells the delegate the interstitial is to be animated off the screen.
- (void)interstitialWillDismissScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will be dismissed.");
}

/// Tells the delegate the interstitial had been animated off the screen.
- (void)interstitialDidDismissScreen:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad dismissed.");
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
- (void)interstitialWillLeaveApplication:(GADInterstitial *)ad {
  NSLog(@"Interstitial ad will leave application.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                              request: request,
                    completionHandler: { (ad, error) in
                      if let error = error {
                        print(error.localizedDescription)
                        return
                      }
                      self.interstitial = ad
                      self.interstitial.fullScreenContentDelegate = self
                    }
  )
}

func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did present full screen content.")
}

func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
  print("Ad failed to present full screen content with error \(error.localizedDescription).")
}

func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did dismiss full screen content.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  GADRequest *request = [GADRequest request];
  [GADInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/4411468910"
                              request:request
                    completionHandler:^(GADInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"interstitial:didFailToReceiveAdWithError: %@", [error localizedDescription])
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Ad did present full screen content.");
}

- (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Ad failed to present full screen content with error %@.", [error localizedDescription]);
}

- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Ad did dismiss full screen content.");
}

Được thưởng

Tải quảng cáo

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADRewardedAdDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
    rewardedAd.delegate = self
    rewardedAd?.load(GADRequest()) { error in
      if let error = error {
        print("Rewarded ad failed to load with error: \(error.localizedDescription)")
      } else {
        print("Rewarded ad loaded.")
      }
    }
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.rewardedAd = [[GADRewardedAd alloc]
      initWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"];
  self.rewardedAd.delegate = self;
  GADRequest *request = [GADRequest request];
  [self.rewardedAd loadRequest:request completionHandler:^(GADRequestError * _Nullable error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
    } else {
      NSLog(@"Rewarded ad loaded.");
    }
  }];
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print("Rewarded ad failed to load with error: \(error.localizedDescription)")
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  GADRequest *request = [GADRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

Quảng cáo hiển thị và xử lý phần thưởng

Quảng cáo có tặng thưởng yêu cầu bạn xử lý sự kiện khi người dùng nhận được phần thưởng. Với phiên bản 7 của API GADRewardedAd, bạn triển khai rewardedAd:userDidEarnReward: như một phần của giao thức GADRewardedAdDelegate. Đối với phiên bản 8, bạn triển khai GADUserDidEarnRewardHandler để hiển thị quảng cáo.

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the user earned a reward.
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarnReward: GADAdReward) {
  // TODO: Reward the user.
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the user earned a reward.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd userDidEarnReward:(GADAdReward *)reward {
  // TODO: Reward the user.
}

v8

Swift

func showRewardedAd() {
  ...
  if let ad = rewardedAd {
      ad.present(fromRootViewController: self,
               userDidEarnRewardHandler: {
                 let reward = ad.adReward
                 // TODO: Reward the user.
               }
      )
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd) {
    [self.rewardedAd presentFromRootViewController:self
                          userDidEarnRewardHandler:^ {
      GADAdReward *reward = self.rewardedAd.adReward;
      // TODO: Reward the user.
    }];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

Sự kiện quảng cáo trình bày

Với GADRewardedAd API, bạn truyền GADRewardedAdDelegate đến phương thức hiển thị quảng cáo. Với API GADRewardedAd, bạn đặt GADFullscreenContentDelegate làm thuộc tính trên quảng cáo trước khi hiển thị quảng cáo.

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the rewarded ad was presented.
- (void)rewardedAdDidPresent:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd didFailToPresentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
        [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)rewardedAdDidDismiss:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad dismissed.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GADRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print(error.localizedDescription)
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
}

/// Tells the delegate that the rewarded ad was presented.
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func ad(_ ad: GADFullScreenPresentingAd,
    didFailToPresentFullScreenContentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  GADRequest *request = [GADRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

/// Tells the delegate that the rewarded ad was presented.
- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)ad:(id)ad
    didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
       [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad dismissed.");
}

Xoá API GADrewardedBasedVideoAd cũ

API GADRewardedAd mới được ra mắt lần đầu vào tháng 3 năm 2019 và là API có tặng thưởng được ưa thích trong hơn 18 tháng qua. API này có nhiều tính năng nâng cao hơn so với API GADRewardedBasedVideoAd cũ, kể cả khả năng tải nhiều quảng cáo có tặng thưởng cùng lúc.

API GADRewardedBasedVideoAd cũ sẽ bị xóa trong SDK phiên bản 8.0.0.

Biểu ngữ thông minh sẽ ngừng hoạt động và được thay thế bằng biểu ngữ thích ứng

Quảng cáo biểu ngữ thông minh sẽ ngừng hoạt động và được thay thế bằng quảng cáo biểu ngữ thích ứng. Biểu ngữ thích ứng mang lại hiệu quả hoạt động vượt trội và tính linh hoạt cao hơn trong việc đặt chiều rộng quảng cáo. Nếu muốn tiếp tục sử dụng biểu ngữ có chiều rộng đầy đủ, bạn vẫn có thể làm vậy bằng cách sử dụng biểu ngữ thích ứng, theo cách minh họa trong đoạn mã sau đây:

Swift

class ViewController: UIViewController {

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Note: The safe area is not known until viewWillAppear.
    let adSize = getFullWidthAdaptiveAdSize()
  }

  func getFullWidthAdaptiveAdSize() -> GADAdSize {
    // Here safe area is taken into account, hence the view frame is used after the
    // view has been laid out.
    let frame = { () -> CGRect in
      if #available(iOS 11.0, *) {
        return view.frame.inset(by: view.safeAreaInsets)
      } else {
        return view.frame
      }
    }()
    return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width)
  }
}

Objective-C

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  // Note: The safe area is not known until viewWillAppear.
  GADAdSize adSize = [self getFullWidthAdaptiveAdSize];
}

- (GADAdSize)getFullWidthAdaptiveAdSize {
  CGRect frame = self.view.frame;
  // Here safe area is taken into account, hence the view frame is used after
  // the view has been laid out.
  if (@available(iOS 11.0, *)) {
    frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  }
  return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width);
}

@end

Xóa lệnh gọi lại ứng dụng

Lệnh gọi lại willLeaveApplication cho tất cả các định dạng quảng cáo đã bị xoá và thay vào đó là các phương thức applicationDidEnterBackground:sceneDidEnterBackground:. Khi sử dụng API ở cấp hệ điều hành, bạn sẽ nhận được thông báo mỗi khi người dùng rời khỏi ứng dụng, bất kể việc đó có phải là do một hành động tương tác với quảng cáo hay không.

Xin lưu ý rằng lệnh gọi lại willLeaveApplication không bao giờ có mục đích là trình xử lý lượt nhấp vào quảng cáo và việc dựa vào lệnh gọi lại này để báo cáo lượt nhấp sẽ không cung cấp chỉ số chính xác. Ví dụ: một lượt nhấp vào biểu tượng Lựa chọn quảng cáo làm khởi chạy một trình duyệt bên ngoài đã kích hoạt lệnh gọi lại, nhưng không được tính là một lượt nhấp.

Đổi tên các lớp

Bảng dưới đây liệt kê các lớp cụ thể đã đổi tên trong phiên bản 8. Tóm tắt:

  • Tất cả các lớp có liên quan đến GADUnifiedNativeAd đều đã được đổi tên thành GADNativeAd.
  • GADRewardBasedVideoAd, GADNativeExpressAdViewGADInstreamAd đã bị xoá.
  • Tất cả các lớp có tiền tố DFP đều đã được thay thế bằng tiền tố GAM.
Lớp phiên bản 7.68.0 Lớp phiên bản 8.0.0
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial Quảng cáo xen kẽ GAM
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADWorkManager NavHostAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
Trình kết nối Quảng cáo lớp học tùy chỉnh
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Đã xóa
GADInterstitial GADInterstitialAd
GADNativeExpressAdView Đã xóa
GADConsentAd Đã xóa
Lớp GADGAD Đã xóa
GADInstreamAdView Đã xóa

Xóa/thay thế một số phương thức

Bảng dưới đây liệt kê các thay đổi cụ thể trong phiên bản 8. Tóm tắt:

  • Các phương thức và thuộc tính bị ngừng sử dụng trước đây đều đã bị xoá.
  • Các phương thức uỷ quyền -willLeaveApplication: đã bị xoá cho mọi định dạng.
  • Tên lớp mạng quảng cáo đã chuyển sang thuộc tính GADResponseInfo.
  • Mã nhận dạng thiết bị thử nghiệm đã chuyển sang thuộc tính GADRequestConfiguration.
Lớp phiên bản 7.68.0 API phiên bản 7.68.0 API phiên bản 8.0.0 Ghi chú
GADMobileAds +configureWithApplicationID: -startWithCompletionHandler: Mã ứng dụng hiện được đặt trong tệp Info.plist.
+disableAutomaticInAppBáo cáo mua hàng -disableAutomaticInAppBáo cáo mua hàng
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices MMMConfiguration.testdeviceidentifiers Thuộc tính testDeviceIdentifiers sẽ áp dụng cho tất cả các yêu cầu quảng cáo, trong khi thuộc tính testDevices cũ được đặt theo yêu cầu.
gender Đã xóa
sinh nhật Đã xóa
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayWithMonth:day:year: Đã xóa
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
GADErrorCode kGADError* Lỗi GADError* Tiền tố k bị loại bỏ khỏi tất cả các hằng số mã lỗi.
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate Đã xóa
mediatedAdView Đã xóa
adNetworkClassName phản hồi.adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions -adSizedelegate Đã xóa
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: Đã xóa
Trình kết nối templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
IframeAdImageAdLoaderOptions preferredImageOrientation IframeAdMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Đã xóa
isReady Đã xóa Thay vào đó, hãy sử dụng canPresentFromRootViewController:error:.
hasBeenUsed Đã xóa
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName phản hồi.adNetworkClassName
-InterstitialWillLeaveApplication: Đã xóa
GADWorkManager videoController mediaContent.videoController
adNetworkClassName phản hồi.adNetworkClassName