Hiển thị định dạng quảng cáo gốc do hệ thống xác định
Khi quảng cáo gốc tải, ứng dụng của bạn sẽ nhận được một đối tượng quảng cáo gốc bằng cách sử dụng một trong các thông báo giao thức GADAdLoaderDelegate. Sau đó, ứng dụng của bạn sẽ chịu trách nhiệm
hiển thị quảng cáo (nhưng không nhất thiết phải hiển thị ngay lập tức).
Để việc hiển thị định dạng quảng cáo do hệ thống xác định trở nên dễ dàng hơn, SDK sẽ cung cấp cho bạn một số tài nguyên
hữu ích.
GADNativeAdView
Đối với GADNativeAd, có một lớp "chế độ xem quảng cáo" tương ứng: GADNativeAdView.
Lớp chế độ xem quảng cáo này là một UIView mà nhà xuất bản nên sử dụng để hiển thị quảng cáo.
Ví dụ: một GADNativeAdView có thể hiển thị một thực thể của GADNativeAd. Mỗi đối tượng UIView dùng để hiển thị thành phần của quảng cáo đó phải là thành phần hiển thị phụ của đối tượng GADNativeAdView đó.
Ví dụ: nếu bạn đang hiển thị quảng cáo trong UITableView, thì hệ phân cấp view cho một trong các ô có thể có dạng như sau:

Lớp GADNativeAdView cũng cung cấp IBOutlets dùng để đăng ký
chế độ xem được dùng cho từng thành phần riêng lẻ và một phương thức để đăng ký
chính đối tượng GADNativeAd. Việc đăng ký các thành phần hiển thị theo cách này cho phép SDK tự động xử lý các tác vụ như:
- Ghi lại lượt nhấp.
- Ghi lại lượt hiển thị (khi pixel đầu tiên xuất hiện trên màn hình).
- Hiển thị lớp phủ Lựa chọn quảng cáo.
Lớp phủ Lựa chọn quảng cáo
Đối với quảng cáo gốc gián tiếp (được phân phối thông qua quảng cáo thay thế của AdMob hoặc thông qua Ad Exchange hoặc AdSense), SDK sẽ thêm lớp phủ Lựa chọn quảng cáo. Để trống một khoảng không gian ở góc mà bạn muốn trong chế độ xem quảng cáo gốc để chèn biểu tượng Lựa chọn quảng cáo tự động. Đồng thời, hãy chắc chắn rằng lớp phủ Lựa chọn quảng cáo được đặt trên nội dung cho phép người dùng nhìn thấy rõ biểu tượng đó. Để biết thêm thông tin về giao diện và chức năng của lớp phủ, hãy xem nguyên tắc triển khai quảng cáo gốc có lập trình.
Thuộc tính quảng cáo
Khi hiển thị quảng cáo gốc có lập trình, bạn phải hiển thị thuộc tính quảng cáo để cho biết rằng chế độ xem đó là một quảng cáo.Ví dụ về mã
Phần này cho biết cách hiển thị quảng cáo gốc bằng cách sử dụng các thành phần hiển thị được tải động từ tệp xib. Đây có thể là một phương pháp rất hữu ích khi sử dụng GADAdLoaders được định cấu hình để yêu cầu nhiều định dạng.
Bố trí UIView
Bước đầu tiên là bố trí UIViews sẽ hiển thị các thành phần quảng cáo gốc.
Bạn có thể làm việc này trong Trình tạo giao diện, giống như khi tạo bất kỳ tệp xib nào khác. Sau đây là bố cục của một quảng cáo gốc:

Hãy chú ý tới giá trị Lớp tuỳ chỉnh ở góc trên cùng bên phải của hình ảnh. Chế độ này được đặt thành
GADNativeAdView.
Đây là lớp chế độ xem quảng cáo được dùng để hiển thị GADNativeAd.
Bạn cũng cần đặt lớp tuỳ chỉnh cho GADMediaView, được dùng để hiển thị video hoặc hình ảnh cho quảng cáo.
Liên kết các cửa hàng với chế độ xem
Sau khi các thành phần hiển thị đã sẵn sàng và bạn đã chỉ định đúng lớp thành phần hiển thị quảng cáo cho bố cục, hãy liên kết các đầu ra thành phần của thành phần hiển thị quảng cáo với UIViews mà bạn đã tạo.
Dưới đây là cách bạn có thể liên kết các cửa hàng thành phần của chế độ xem quảng cáo với UIViews được tạo cho một quảng cáo:

Trong bảng điều khiển đầu ra, các đầu ra trong GADNativeAdView đã được liên kết với UIViews được bố trí trong Trình tạo giao diện. Điều này giúp SDK biết UIView nào hiển thị thành phần nào.
Bạn cũng cần nhớ rằng những kênh này thể hiện quan điểm có thể nhấp vào trong quảng cáo.
Hiển thị quảng cáo
Sau khi hoàn tất bố cục và liên kết các đầu ra, hãy thêm mã sau vào ứng dụng của bạn để hiển thị quảng cáo sau khi tải xong:
Swift
func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) {
// ...
// Set ourselves as the native ad delegate to be notified of native ad events.
nativeAd.delegate = self
// Populate the native ad view with the native ad assets.
// The headline and mediaContent are guaranteed to be present in every native ad.
(nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent
// Some native ads will include a video asset, while others do not. Apps can use the
// GADVideoController's hasVideoContent property to determine if one is present, and adjust their
// UI accordingly.
let mediaContent = nativeAd.mediaContent
if mediaContent.hasVideoContent {
// By acting as the delegate to the GADVideoController, this ViewController receives messages
// about events in the video lifecycle.
mediaContent.videoController.delegate = self
videoStatusLabel.text = "Ad contains a video asset."
} else {
videoStatusLabel.text = "Ad does not contain a video."
}
// This app uses a fixed width for the GADMediaView and changes its height to match the aspect
// ratio of the media it displays.
if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
let aspectRatioConstraint = NSLayoutConstraint(
item: mediaView,
attribute: .width,
relatedBy: .equal,
toItem: mediaView,
attribute: .height,
multiplier: CGFloat(nativeAd.mediaContent.aspectRatio),
constant: 0)
mediaView.addConstraint(aspectRatioConstraint)
nativeAdView.layoutIfNeeded()
}
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
(nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
nativeAdView.bodyView?.isHidden = nativeAd.body == nil
(nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil
(nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
nativeAdView.iconView?.isHidden = nativeAd.icon == nil
(nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)
nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil
(nativeAdView.storeView as? UILabel)?.text = nativeAd.store
nativeAdView.storeView?.isHidden = nativeAd.store == nil
(nativeAdView.priceView as? UILabel)?.text = nativeAd.price
nativeAdView.priceView?.isHidden = nativeAd.price == nil
(nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil
// In order for the SDK to process touch events properly, user interaction should be disabled.
nativeAdView.callToActionView?.isUserInteractionEnabled = false
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
// Note: this should always be done after populating the ad views.
nativeAdView.nativeAd = nativeAd
}
SwiftUI
Tạo mô hình khung hiển thị
Tạo một mô hình khung hiển thị tải quảng cáo gốc và xuất bản các thay đổi về dữ liệu quảng cáo gốc:
import GoogleMobileAds
class NativeAdViewModel: NSObject, ObservableObject, NativeAdLoaderDelegate {
@Published var nativeAd: NativeAd?
private var adLoader: AdLoader!
func refreshAd() {
adLoader = AdLoader(
adUnitID: "ca-app-pub-3940256099942544/3986624511",
// The UIViewController parameter is optional.
rootViewController: nil,
adTypes: [.native], options: nil)
adLoader.delegate = self
adLoader.load(Request())
}
func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) {
// Native ad data changes are published to its subscribers.
self.nativeAd = nativeAd
nativeAd.delegate = self
}
func adLoader(_ adLoader: AdLoader, didFailToReceiveAdWithError error: Error) {
print("\(adLoader) failed with error: \(error.localizedDescription)")
}
}
Tạo UIViewRepresentable
Tạo một
UIViewRepresentable
cho NativeView và đăng ký nhận thông báo khi dữ liệu thay đổi trong lớp ViewModel:
private struct NativeAdViewContainer: UIViewRepresentable {
typealias UIViewType = NativeAdView
// Observer to update the UIView when the native ad value changes.
@ObservedObject var nativeViewModel: NativeAdViewModel
func makeUIView(context: Context) -> NativeAdView {
return
Bundle.main.loadNibNamed(
"NativeAdView",
owner: nil,
options: nil)?.first as! NativeAdView
}
func updateUIView(_ nativeAdView: NativeAdView, context: Context) {
guard let nativeAd = nativeViewModel.nativeAd else { return }
// Each UI property is configurable using your native ad.
(nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent
(nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
(nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
(nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)
(nativeAdView.storeView as? UILabel)?.text = nativeAd.store
(nativeAdView.priceView as? UILabel)?.text = nativeAd.price
(nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
(nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
// For the SDK to process touch events properly, user interaction should be disabled.
nativeAdView.callToActionView?.isUserInteractionEnabled = false
// Associate the native ad view with the native ad object. This is required to make the ad
// clickable.
// Note: this should always be done after populating the ad views.
nativeAdView.nativeAd = nativeAd
}
Thêm khung hiển thị vào hệ phân cấp view
Mã sau đây minh hoạ cách thêm UIViewRepresentable vào hệ phân cấp khung hiển thị:
struct NativeContentView: View {
// Single source of truth for the native ad data.
@StateObject private var nativeViewModel = NativeAdViewModel()
var body: some View {
ScrollView {
VStack(spacing: 20) {
// Updates when the native ad data changes.
NativeAdViewContainer(nativeViewModel: nativeViewModel)
.frame(minHeight: 300) // minHeight determined from xib.
Objective-C
- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeAd:(GADNativeAd *)nativeAd {
// ...
GADNativeAdView *nativeAdView = self.nativeAdView;
// Set ourselves as the ad delegate to be notified of native ad events.
nativeAd.delegate = self;
// Populate the native ad view with the native ad assets.
// The headline and mediaContent are guaranteed to be present in every native ad.
((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;
nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;
// This app uses a fixed width for the GADMediaView and changes its height
// to match the aspect ratio of the media content it displays.
if (nativeAdView.mediaView != nil && nativeAd.mediaContent.aspectRatio > 0) {
NSLayoutConstraint *aspectRatioConstraint =
[NSLayoutConstraint constraintWithItem:nativeAdView.mediaView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nativeAdView.mediaView
attribute:NSLayoutAttributeHeight
multiplier:(nativeAd.mediaContent.aspectRatio)
constant:0];
[nativeAdView.mediaView addConstraint:aspectRatioConstraint];
[nativeAdView layoutIfNeeded];
}
if (nativeAd.mediaContent.hasVideoContent) {
// By acting as the delegate to the GADVideoController, this ViewController
// receives messages about events in the video lifecycle.
nativeAd.mediaContent.videoController.delegate = self;
self.videoStatusLabel.text = @"Ad contains a video asset.";
} else {
self.videoStatusLabel.text = @"Ad does not contain a video.";
}
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;
[((UIButton *)nativeAdView.callToActionView) setTitle:nativeAd.callToAction
forState:UIControlStateNormal];
nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;
((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;
((UIImageView *)nativeAdView.starRatingView).image = [self imageForStars:nativeAd.starRating];
nativeAdView.starRatingView.hidden = nativeAd.starRating ? NO : YES;
((UILabel *)nativeAdView.storeView).text = nativeAd.store;
nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;
((UILabel *)nativeAdView.priceView).text = nativeAd.price;
nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;
((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;
// In order for the SDK to process touch events properly, user interaction
// should be disabled.
nativeAdView.callToActionView.userInteractionEnabled = NO;
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
// Note: this should always be done after populating the ad views.
nativeAdView.nativeAd = nativeAd;
}
Ví dụ hoàn chỉnh trên GitHub
Xem ví dụ hoàn chỉnh về cách tích hợp quảng cáo gốc trong Swift, SwiftUI và Objective-C bằng cách nhấp vào đường liên kết tương ứng đến GitHub.
Ví dụ về quảng cáo gốc nâng cao bằng Swift Ví dụ về quảng cáo gốc bằng SwiftUI Ví dụ về quảng cáo gốc nâng cao bằng Objective-CGADMediaView
Thành phần hình ảnh và video được hiển thị cho người dùng bằng cách sử dụng
GADMediaView.
Đây là một UIView có thể được xác định trong tệp xib hoặc được tạo động.
Thành phần hiển thị này phải được đặt trong hệ phân cấp view của GADNativeAdView, giống như mọi thành phần hiển thị khác của thành phần.
Giống như tất cả các chế độ xem thành phần, chế độ xem nội dung nghe nhìn cần phải có nội dung. Bạn có thể thiết lập giá trị này bằng thuộc tính mediaContent trên GADMediaView. Thuộc tính mediaContent của GADNativeAd chứa nội dung nghe nhìn có thể được truyền đến GADMediaView.
Dưới đây là một đoạn mã trong ví dụ về quảng cáo gốc nâng cao
(Swift |
Objective-C)
cho biết cách điền thành phần quảng cáo gốc GADMediaView bằng cách sử dụng
GADMediaContent từ GADNativeAd:
Swift
nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent
Objective-C
nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;
Đảm bảo rằng trong tệp trình tạo giao diện cho chế độ xem quảng cáo gốc, bạn đã đặt lớp tuỳ chỉnh của chế độ xem thành GADMediaView và đã kết nối lớp đó với đầu ra mediaView.
Thay đổi chế độ nội dung hình ảnh
Lớp GADMediaView tuân thủ thuộc tính UIView
contentMode
khi hiển thị hình ảnh. Nếu bạn muốn thay đổi cách điều chỉnh tỷ lệ hình ảnh trong GADMediaView, hãy đặt UIViewContentMode tương ứng trên thuộc tính contentMode của GADMediaView để đạt được điều này.
Ví dụ: để lấp đầy GADMediaView khi hình ảnh xuất hiện (quảng cáo không có video):
Swift
nativeAdView.mediaView?.contentMode = .scaleAspectFit
Objective-C
nativeAdView.mediaView.contentMode = UIViewContentModeScaleAspectFit;
GADMediaContent
Lớp GADMediaContent
chứa dữ liệu liên quan đến nội dung nghe nhìn của quảng cáo gốc. Nội dung này được hiển thị bằng cách
sử dụng lớp GADMediaView. Khi được đặt trên thuộc tính GADMediaView
mediaContent:
Nếu có thành phần video, thì video đó sẽ được lưu vào vùng đệm và bắt đầu phát bên trong
GADMediaView. Bạn có thể biết thành phần video có sẵn hay không bằng cách kiểm trahasVideoContent.Nếu quảng cáo không chứa thành phần video, thì thành phần
mainImagesẽ được tải xuống và đặt bên trongGADMediaView.
Các bước tiếp theo
Tìm hiểu thêm về quyền riêng tư của người dùng.