Hiển thị định dạng quảng cáo gốc do hệ thống xác định
Khi một 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 thông qua 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à UIView
mà nhà xuất bản nên sử dụng để hiển thị quảng cáo.
Ví dụ: một GADNativeAdView
duy nhất có thể hiển thị một bản sao của GADNativeAd
. Mỗi đối tượng UIView
được dùng để hiển thị tài sản của quảng cáo đó phải là chế độ xem phụ của đối tượng GADNativeAdView
đó.
Ví dụ: nếu bạn đang hiển thị một quảng cáo trong UITableView
, hệ phân cấp chế độ xem cho một trong các ô có thể trông như sau:
Lớp GADNativeAdView
cũng cung cấp IBOutlets
dùng để đăng ký chế độ xem cho từng tài sả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 chế độ xem theo cách này cho phép SDK tự động xử lý các công việc như:
- Ghi lại các lượt nhấp.
- Ghi lại các lượt hiển thị (khi pixel đầu tiên hiển thị 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 (phân phát qua tính năng chèn lấp AdMob hoặc qua Ad Exchange hay AdSense), SDK sẽ thêm một lớp phủ Lựa chọn quảng cáo. Hãy để trống một khoảng ở góc bạn muốn đặt chế độ xem quảng cáo gốc để hệ thống tự động chèn biểu trưng Lựa chọn quảng cáo. Ngoài ra, hãy đảm bảo 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 dễ dàng nhìn thấy 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ị một thuộc tính quảng cáo để biểu thị rằng chế độ xem đó là quảng cáo.Ví dụ về mã
Hãy cùng tìm hiểu cách hiển thị quảng cáo gốc sử dụng các chế độ xem được tải động từ các 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.
Sắp xếp bố cục cho UIViews
Bước đầu tiên cần làm là sắp xếp bố cục cho UIViews
, chế độ xem này sẽ hiển thị 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. Dưới đây là hình thức hiển thị của bố cục 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. Giá trị được đặt thành
GADNativeAdView
.
Đây là lớp chế độ xem quảng cáo được dùng để hiển thị một GADNativeAd
.
Ngoài ra, bạn cũng cần đặt lớp tuỳ chỉnh cho GADMediaView
, lớp này được dùng để hiển thị video hoặc hình ảnh cho quảng cáo.
Liên kết các đầu ra với chế độ xem
Sau khi các chế độ xem đã sẵn sàng và bạn đã chỉ định đúng lớp chế độ xem quảng cáo cho bố cục, hãy liên kết đầu ra tài sản của chế độ xem quảng cáo với UIViews
mà bạn đã tạo.
Dưới đây là cách liên kết đầu ra nội dung của chế độ xem quảng cáo với UIViews
đã tạo
cho quảng cáo:
Trong bảng điều khiển đầu ra, các đầu ra trong GADNativeAdView
đã liên kết với UIViews
được bố trí trong Trình tạo giao diện. Điều này cho phép SDK biết được tài sản hiển thị tương ứng của các UIView
.
Ngoài ra, bạn cũng nên nhớ rằng các đầu ra này đại diện cho các chế độ xem có thể nhấp vào trong quảng cáo.
Hiển thị quảng cáo
Sau khi bố cục hoàn tất và các đầu ra được liên kết, hãy thêm mã sau vào ứng dụng của bạn để hiển thị quảng cáo sau khi quảng cáo tải:
Swift
// Mark: - NativeAdLoaderDelegate
func adLoader(_ adLoader: AdLoader, didReceive nativeAd: NativeAd) {
print("Received native ad: \(nativeAd)")
refreshAdButton.isEnabled = true
// Create and place ad in view hierarchy.
let nibView = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil)?.first
guard let nativeAdView = nibView as? NativeAdView else {
return
}
setAdView(nativeAdView)
// 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
// This app uses a fixed width for the MediaView and changes its height to match the aspect
// ratio of the media it displays.
if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
let heightConstraint = NSLayoutConstraint(
item: mediaView,
attribute: .height,
relatedBy: .equal,
toItem: mediaView,
attribute: .width,
multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio),
constant: 0)
heightConstraint.isActive = true
}
// 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(
fromStarRating: 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
// 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ột 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 một 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 khung hiển thị
Đoạn 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
#pragma mark GADNativeAdLoaderDelegate implementation
- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeAd:(GADNativeAd *)nativeAd {
NSLog(@"Received native ad: %@", nativeAd);
self.refreshButton.enabled = YES;
// Create and place ad in view hierarchy.
GADNativeAdView *nativeAdView =
[[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
[self setAdView:nativeAdView];
// Set the mediaContent on the GADMediaView to populate it with available
// video/image asset.
nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;
// Populate the native ad view with the native ad assets.
// The headline is present in every native ad.
((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;
// 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.
nativeAdView.nativeAd = nativeAd;
}
Ví dụ hoàn chỉnh trên GitHub
Xem ví dụ đầy đủ 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 trê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 hiển thị cho người dùng thông qua GADMediaView
.
Đây là một UIView
có thể được xác định trong tệp xib hoặc được thiết lập động.
Bạn phải đặt chế độ xem này bên trong hệ phân cấp chế độ xem của GADNativeAdView
, giống như
mọi chế độ xem tài sản khác.
Tương tự như với tất cả các chế độ xem tài sản khác, bạn phải điền nội dung vào chế độ xem nội dung nghe nhìn. Điều này được đặt bằng cách sử dụng thuộc tính mediaContent
trên GADMediaView
. Hệ thống có thể chuyển thuộc tính mediaContent
của GADNativeAd
chứa nội dung nghe nhì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;
Hãy đả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 chế độ xem thành GADMediaView
và bạn đã kết nối lớp đó với đầu ra mediaView
.
Thay đổi chế độ nội dung hình ảnh
Lớp GADMediaView
áp dụng thuộc tính UIView
contentMode
khi hiển thị hình ảnh. Nếu bạn muốn thay đổi cách chuyển 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ụ: để điền vào GADMediaView
khi hiển thị hình ảnh (quảng cáo không có
video):
Swift
nativeAdView.mediaView?.contentMode = .aspectFill
Objective-C
nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;
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 bạn đặt 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 liệu quảng cáo có chứa tài sản video hay không bằng cách đánh dấu chọnhasVideoContent
.Nếu quảng cáo không chứa thành phần video, thì thành phần
mainImage
sẽ đượ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.